我想将其他编码中的数据转换为UTF-8。我陷入了以下问题:
pointer being freed was not allocated
。
为什么iconv与我的记忆一起玩?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;
}
答案 0 :(得分:3)
来自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);
outbuf指向的变量应更新为指向转换后的输出数据的最后一个字节后面的字节。
您需要在*dst
功能中保存并恢复*src
(以及可能utf8()
)。