c - How to use iconv for utf8 conversion? -
i want convert data in other encodings utf-8. i'm stranded following problems:
- executing attached code gives me:
pointer being freed not allocated
in iconv(). why iconv play memory? - when don't free(dst) doesn't crash nothing printed. not 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; // enough ascii 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 iconv()
description @ 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 outbuf shall updated point byte following last byte of converted output data.
you need save , restore *dst
(and possibly *src
) inside utf8()
function.
Comments
Post a Comment