How to use iconv to convert utf8?

I want to convert data to other encodings in UTF-8. I encountered the following problems:

  • Executing the attached code gives me: pointer being freed was not allocatedin iconv (). Why does iconv play with my memory?
  • When I do not free (dst), it does not crash, but nothing is printed. Even gibberish. What's wrong?

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;
}
+5
source share
1 answer

Quote from the iconv()description on 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 specified by outbuf must be updated to indicate the byte after the last byte of the converted output.

You need to save and restore *dst(and possibly *src) inside your function utf8().

+3
source

All Articles