0

Whenever I create a char* with malloc(), the first few bytes get random data, which is different every time I compile the code. In this case, I wanted to concatenate 2 char* to create 1 char*.

char *JoinStrings(char *str1, char *str2) { int length = strlen(str1) + strlen(str2) + 1; char *newString = malloc(length); if (newString == NULL) { printf("malloc failed\n"); return NULL; } newString[length] = 0; // add the 0 byte at the end printf("String 1: %s\n", str1); printf("String 2: %s\n", str2); printf("New String: %s\n", newString); strcat(newString, str1); strcat(newString, str2); printf("Joined String: %s\n", newString); return newString; } 

I will call the function using this line:

char *join1 = JoinStrings("Hello,", " World"); 

I would expect it to print out "Joined String: Hello, World" as the last printed message, but it instead returns this:

String 1: Hello, String 2: World New String: p‼√ΓJ☻ Joined String: p‼√ΓJ☻Hello, World 

I have no idea where it gets the random bytes from, and they are randomized every time I compile it. And because it gets randomized when I compile it, here is the GCC version I'm using: gcc.exe (Rev1, Built by MSYS2 project) 11.2.0.

0

1 Answer 1

2

Malloc does not initialise the allocated memory content to any value. As strcat tries to locate the end of the string to concat, anything may happen. So don't use strcat for the first but strcpy:

strcpy(newString,str1); strcat(newString,str2); 

and:

newString[length] = 0; 

should be:

newString[length-1] = 0; 

Last element has index length-1.

Sign up to request clarification or add additional context in comments.

3 Comments

The last element (i.e. index) of a string is indeed "length-1", however the location of the null-terminator is [length]... which I believe was what he was trying to provide. with " newString[length] = 0; // add the 0 byte at the end "
@TonyB No. The number of allocated byte is length, all are indexed through 0..length-1. The terminator NUL char must be in one of these memory cells. Accessing a cell outside these is "Undefined behavior".
You of course are correct. I missed the fact that "length" included the null terminator.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.