简体   繁体   中英

Convert int to string and concatenate the result

I try to concatenate a string with an integer converted into string and write the result into a file.

There is my code (simplified):

char * convert_int_string(int val)
{
  char * str = malloc(sizeof(char)*64);
  sprintf(str,"%d",val);
  return str;
}

char * parse_val(int val){
  char * str = malloc(sizeof(char)*64);
  char * str2 = convert_int_string(val);
  strcat(str, "test");
  strcat(str,str2);
  free(str2);
  return str;
}

fprintf(my_file, "%s\n", parse_val(42));

But I get this result and I don't understand why (here val is equal to 42):

��7s�test42

(I used this post How do I concatenate const/literal strings in C? and this one How to convert integer to string in C? )

The reason why you get garbaged output is because what you give to strcat is garbage. Indeed, you malloc'ed 64 bytes for str but you didn't initialize it, so you don't know which bytes it contains. You can either use calloc instead of malloc or use memset to put 0 in str .

EDIT: In fact, you only need to put \\0 as the first byte of str . Indeed, strcat first looks for the \\0 char in the destination string, from there it adds the second string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM