From f069f6fe69dafb6fdd1276237d7719c7b197daa8 Mon Sep 17 00:00:00 2001 From: Vaclav Dolezal Date: Thu, 14 Dec 2017 15:39:42 +0100 Subject: libfdisk: allocate enough bytes for ucs2 to utf8 encoding Allocate 3*number_of_ucs2_characters bytes for utf8 output. Also as we are using calloc there's no need to write terminating null byte. Signed-off-by: Vaclav Dolezal --- libfdisk/src/gpt.c | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) (limited to 'libfdisk/src') diff --git a/libfdisk/src/gpt.c b/libfdisk/src/gpt.c index d77ed2d2b..8598dbd2e 100644 --- a/libfdisk/src/gpt.c +++ b/libfdisk/src/gpt.c @@ -1634,9 +1634,10 @@ static char *encode_to_utf8(unsigned char *src, size_t count) { uint16_t c; char *dest; - size_t i, j, len = count; + size_t i, j; + size_t len = count * 3 / 2; - dest = calloc(1, count); + dest = calloc(1, len + 1); if (!dest) return NULL; @@ -1644,26 +1645,24 @@ static char *encode_to_utf8(unsigned char *src, size_t count) /* always little endian */ c = (src[i+1] << 8) | src[i]; if (c == 0) { - dest[j] = '\0'; break; } else if (c < 0x80) { - if (j+1 >= len) + if (j+1 > len) break; dest[j++] = (uint8_t) c; } else if (c < 0x800) { - if (j+2 >= len) + if (j+2 > len) break; dest[j++] = (uint8_t) (0xc0 | (c >> 6)); dest[j++] = (uint8_t) (0x80 | (c & 0x3f)); } else { - if (j+3 >= len) + if (j+3 > len) break; dest[j++] = (uint8_t) (0xe0 | (c >> 12)); dest[j++] = (uint8_t) (0x80 | ((c >> 6) & 0x3f)); dest[j++] = (uint8_t) (0x80 | (c & 0x3f)); } } - dest[j] = '\0'; return dest; } -- cgit v1.2.3-55-g7522