Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use iconv for utf8 conversion?

Tags:

c

I want to convert data in other encodings to UTF-8. I'm stranded with following problems:

  1. Executing the attached code gives me: pointer being freed was not allocated in iconv(). Why does iconv play with my memory?
  2. When I don't free(dst) it doesn't crash but nothing is printed. Not 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;
}
like image 841
ClosedID Avatar asked Mar 07 '12 20:03

ClosedID


1 Answers

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.

like image 172
pmg Avatar answered Oct 20 '22 23:10

pmg