简体   繁体   中英

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

char a[] = "hello ";

This declares a char array with exactly 7 elements, the six characters plus \\0 . There's no room for anything to be concatenated.

A simple fix is to reserve more space, if you know how much data you want to add.

char a[12] = "hello ";

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM