I want to convert data in other encodings to UTF-8. I'm stranded with following problems:
pointer being freed was not allocated
in iconv().
Why does iconv play with my memory?void utf8(char **dst, char **src, const char *enc)
{
iconv_t cd;
size_t len_src,
len_dst;
len_src = strlen(*src);
len_dst = len_src * 8; // is that enough for ASCII to UTF8?
cd = iconv_open("UTF-8", enc);
*dst = (char *)calloc(len_dst+1, 1);
iconv(cd, src, &len_src, dst, &len_dst);
iconv_close(cd);
}
int main(int argc, char **argv)
{
char *src = "hello world";
char *dst;
utf8(&dst, &src, "ASCII");
printf("%s\n", dst);
free(dst);
return 0;
}
Quote from iconv()
description at POSIX.1-2008
size_t iconv(iconv_t cd, char **restrict inbuf,
size_t *restrict inbytesleft, char **restrict outbuf,
size_t *restrict outbytesleft);
The variable pointed to by outbuf shall be updated to point to the byte following the last byte of converted output data.
You need to save and restore *dst
(and possibly *src
) inside your utf8()
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With