当在C中连接字符串时“堆栈粉碎检测到”

时间:2016-10-29 16:39:13

标签: c security

我使用此代码在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');

}

字符串连接正确但输出中的下一行是:

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

为什么这个代码被检测为堆栈粉碎?

2 个答案:

答案 0 :(得分:1)

char a[] = "hello ";

这声明了一个char数组,其中包含7个元素,六个字符加上\0。没有任何东西可以连接起来。

如果您知道要添加多少数据,一个简单的解决方法是保留更多空间。

char a[12] = "hello ";

答案 1 :(得分:1)

C中的字符串是设置长度,因此您无法向它们添加内容。您必须创建一个新的并将它们复制到它。由于您正在写入未分配给您的空间,因此会触发错误。你只有7个字节,但是你正在编写第8个,第9个......第12个字节,因此能够写入其他程序数据(粉碎堆栈)。

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