如何使用iconv进行utf8转换?

Clo*_*dID 6 c

我想将其他编码中的数据转换为UTF-8.我陷入了以下问题:

  1. 执行附加的代码给我:pointer being freed was not allocatediconv().为什么iconv与我的记忆一起玩?
  2. 当我不自由(dst)它不会崩溃但没有打印.甚至没有胡言乱语.怎么了?

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;
}
Run Code Online (Sandbox Code Playgroud)

pmg*_*pmg 3

引用自iconv()POSIX.1-2008 的描述

size_t iconv(iconv_t cd, char **restrict inbuf,
       size_t *restrict inbytesleft, char **restrict outbuf,
       size_t *restrict outbytesleft);
Run Code Online (Sandbox Code Playgroud)

outbuf 指向的变量应更新为指向转换后的输出数据的最后一个字节之后的字节。

您需要在函数内部进行保存和恢复*dst(可能还需要*srcutf8()