I am trying to convert string from 'ascii' to 'utf-8', the 'lencoded_str' function will take a pointer char and return another pointer char. the input pointer char size is unknown, and it will change each time the 'lencoded_str' function called. my problem is the 'lencoded_str' function always return nothing.
Any help would be much appreciated.
this is just an example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iconv.h>
char *lencoded_str(char *in_str){
iconv_t iconv_obj = iconv_open("utf-8","ascii");
char *out_str = calloc(strlen(in_str) * 2, sizeof(char));
char *out_str_start = out_str;
size_t in_str_bytes_left = strlen(in_str);
size_t out_str_bytes_left = strlen(in_str) * 2;
int iconv_return = iconv(iconv_obj, &in_str, &in_str_bytes_left, &out_str, &out_str_bytes_left);
iconv_close(iconv_obj);
return out_str;
}
int main( ){
printf("out: %s\n", lencoded_str("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"));
printf("out: %s\n", lencoded_str("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"));
printf("out: %s\n", lencoded_str("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"));
}
iconv
advances toe input and output string pointers so that they point at the end of the converted string.
That means you must save the original value of the char buffer and return it. You've already had the right idea with out_str_start
, but you don't use it:
return out_str_start;
By using the return value from lencoded_str
directly in printf
and not storing it, you will leak the memory that yopu calloc
ed. You could also go easy on the strlen
s; you only need to call it once.