Richard Smith Richard Smith - 1 month ago 7
C Question

"Stack smashing detected" when concatenating strings in C

I used this code to concatenate two strings in C:

int main(int argc, char** argv) {

char a[] = "hello ";
char b[] = "world";

concat(a, b);
printf("%s\n", a);

return (EXIT_SUCCESS);
}

void concat(char s[], char t[]){
int i, j;
i = j = 0;
while (s[i] != '\0') i++;

while ((s[i++]=t[j++]) != '\0');

}


The string was concatenated correctly but the next line in output was:

*** stack smashing detected *** [...] terminated


Why was this code detected as stack smashing?

Answer

Strings in C are set length, thus you can't append something to them. You have to create a new one and copy both to it. The error is triggered because you are writing to a space that wasn't allocated to you. You got only 7 bytes, but you are writing 8th, 9th... 12th byte, thus owerwriting other program data (smashing the stack).

#include <string.h>
char* concat(char s[], char t[]){
    int i, j;
    i = j = 0;
    char* u = (char*)malloc(strlen(s) + strlen(t)+1);//new string with enough space for both and \0
    while (s[i] != '\0') {
        u[i]=s[i];
        i++;
   }
    while ((u[i++]=t[j++]) != '\0');
    return u;
}