comparison mcabber/src/utf8.c @ 326:1bc374915787

Fix crash when utf8_decode parameter is NULL
author Mikael Berthe <mikael@lilotux.net>
date Sun, 17 Jul 2005 15:35:09 +0100
parents 18a03a69f5e4
children 53dfe6aa6a23
comparison
equal deleted inserted replaced
325:ff6fb51bfd78 326:1bc374915787
11 * 11 *
12 * Note: it is up to the caller to free the returned string 12 * Note: it is up to the caller to free the returned string
13 */ 13 */
14 char *utf8_decode(const char *src) 14 char *utf8_decode(const char *src)
15 { 15 {
16 char *ret = calloc(1, strlen(src) + 1); 16 unsigned char *ret;
17 unsigned char *aux = (unsigned char*)ret; 17
18 if (!src) return NULL;
19
20 ret = calloc(1, strlen(src) + 1);
18 21
19 while (*src) { 22 while (*src) {
20 unsigned char lead = *src++; 23 unsigned char lead = *src++;
21 if ((lead & 0xe0) == 0xc0) { 24 if ((lead & 0xe0) == 0xc0) {
22 unsigned char ch2 = *src++; 25 unsigned char ch2 = *src++;
23 *aux = ((lead & 0x1f) << 6) | (ch2 & 0x3f); 26 *ret = ((lead & 0x1f) << 6) | (ch2 & 0x3f);
24 } else { 27 } else {
25 *aux = lead; 28 *ret = lead;
26 } 29 }
27 aux++; 30 ret++;
28 } 31 }
29 32
30 return ret; 33 return (char*)ret;
31 } 34 }
32 35
33 36
34 /* Desc: convert ASCII -> UTF8 37 /* Desc: convert ASCII -> UTF8
35 * 38 *
38 * 41 *
39 * Note: it is up to the caller to free the returned string 42 * Note: it is up to the caller to free the returned string
40 */ 43 */
41 char *utf8_encode(const char *src) 44 char *utf8_encode(const char *src)
42 { 45 {
43 char *ret = calloc(1, (strlen(src) * 2) + 1); 46 unsigned char *ret;
44 unsigned char *aux = (unsigned char*)ret; 47
48 if (!src) return NULL;
49
50 ret = calloc(1, (strlen(src) * 2) + 1);
45 51
46 while (*src) { 52 while (*src) {
47 unsigned char ch = *src++; 53 unsigned char ch = *src++;
48 if (ch < 0x80U) { 54 if (ch < 0x80U) {
49 *aux++ = ch; 55 *ret++ = ch;
50 } else { /* if (ch < 0x800U) { */ 56 } else { /* if (ch < 0x800U) { */
51 *aux++ = 0xc0 | (ch >> 6); 57 *ret++ = 0xc0 | (ch >> 6);
52 *aux++ = 0x80 | (ch & 0x3f); 58 *ret++ = 0x80 | (ch & 0x3f);
53 } 59 }
54 } 60 }
55 61
56 return ret; 62 return (char*)ret;
57 } 63 }