Search code examples
mallocdynamic-memory-allocationstrcat

Why doesn't malloced string not work with strcat?


In the following code, on commenting strcat, str1 is returned as initially declared till word "Enjoy" but on using strcat, it throws segfault. I am confused why concatenation is not taking place since I declared a dynamic allocated string.

char * kitchen(int cost)
    {
        cost = 100;
        char *str1 = (char *)malloc(sizeof(char)* 70);
        str1 = "\n Food's ready bruh, Enjoyy!!";
        char *str2 = (char *)malloc(sizeof(char)* 70);
        sprintf(str2, " But do pay %d", cost );
        strcat(str1, str2);
        return str1;
    }

Solution

  • Replace

    str1 = "\n Food's ready bruh, Enjoyy!!";
    

    With

    strcpy(str1, "\n Food's ready bruh, Enjoyy!!");
    

    Live demo here.

    Despite your dynamic allocation, "\n Food's ready bruh, Enjoyy!!" is still a string literal, and is still treated by C as read-only. Your assignment merely points str1 to that string literal.