Home > database >  Frist few bytes of a char* are corrupted after creating it with malloc()
Frist few bytes of a char* are corrupted after creating it with malloc()

Time:07-17

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.

CodePudding user response:

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.

  • Related