- 论坛徽章:
- 0
|
原来一直以为是平台问题,现在发现用下面一段代码是成功的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iconv.h>
int Convert(char* encFrom, char* encTo, const char* in, int in_len, char* out, int out_len)
{
char* sin, *sout;
int ret;
iconv_t c_pt;
printf("1\n");
if((c_pt = iconv_open(encTo, encFrom)) == (iconv_t)-1)
{
printf("c_pt == -1\n");
return -1;
}
iconv(c_pt, NULL, NULL, NULL, NULL);
sin = (char*)in;
sout = (char*)out;
printf("2\n");
ret = iconv(c_pt, &sin, (size_t*)&in_len, &sout, (size_t*)&out_len);
printf("3\n");
if(ret == -1)
{
iconv_close(c_pt);
printf("iconv error\n");
return -1;
}
iconv_close(c_pt);
return 1;
}
int main()
{
char buf[50];
char* str = "1234 abc nimen";
memset(buf, '\0', sizeof(buf));
Convert("hp15CN", "utf8", str, strlen(str)+1, buf, sizeof(buf));
printf("buf = %s\n", buf);
} |
output:
1
2
3
buf = 1234 abc nimen
简单的测试代码成功了,可程序里的代码却会coredump,我要疯了
程序中的代码
int Convert(char* encFrom, char* encTo, const char* in, int in_len, char* out, int out_len)
{
char* bufin = NULL;
char* bufout = NULL;
char* sin, *sout;
int ret;
iconv_t c_pt;
int ilen, olen;
printf("1\n");
if((c_pt = iconv_open(encTo, encFrom)) == (iconv_t)-1)
{
printf("c_pt == -1\n");
return GBK_TO_UTF8_ERROR;
}
iconv(c_pt, NULL, NULL, NULL, NULL);
printf("2\n");
bufin = (char*)malloc(in_len);
if(bufin == NULL)
return GBK_TO_UTF8_ERROR;
memset(bufin, '\0', sizeof(bufin));
/*strcpy(bufin, in);*/
strcpy(bufin, "wo men ke");
printf("in str len = %d\n", strlen(in));
printf("bufin=%s\n", bufin);
sin = bufin;
sout = bufout;
ilen = strlen(bufin)+1;
olen = 495;
printf("3\n");
printf("sin=%s, sout=%s, ilen=%d, olen=%d\n", sin, out, ilen, olen);
ret = iconv(c_pt, &sin,(size_t*)&ilen, &sout, (size_t*)&olen);
printf("4\n");
if(ret == -1)
{
iconv_close(c_pt);
if(bufin != NULL)
{
free(bufin);
bufin = NULL;
}
printf("iconv error\n");
return GBK_TO_UTF8_ERROR;
}
if(bufin != NULL)
{
free(bufin);
bufin = NULL;
}
iconv_close(c_pt);
return SUCCEED;
}
|
output:
1
2
in str len = 22
bufin=wo men ke
3
sin=wo men ke, sout=, ilen=10, olen=495
Bus error(coredump) |
|