0

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?)

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Eraseth
  • 503
  • 1
  • 6
  • 19
  • 4
    `strcat(str, "test");` --> `strcpy(str, "test");` : The memory chunk returned by `malloc` is not initialized. – BLUEPIXY Jan 14 '17 at 23:51
  • 1
    `str` in `parse_val()` has been allocated memory but you cannot `concat` without initialising that memory. – Weather Vane Jan 14 '17 at 23:52
  • Nice, thanks @BLUEPIXY. Works well – Eraseth Jan 14 '17 at 23:55
  • in `strcat(str, "test");` line you concaenate allocated but uninitialized string t=with string "test". But there is some garbage data in that uninitialized memory, so you get in resulted string part of that garbage till the first zero byte which in `C` means the end of the string – SergeyLebedev Jan 14 '17 at 23:56

1 Answers1

2

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

Omar
  • 943
  • 6
  • 9