简体   繁体   English

在C中串联字符串时“检测到堆栈崩溃”

[英]“Stack smashing detected” when concatenating strings in C

I used this code to concatenate two strings in C: 我使用此代码在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 . 这将声明一个恰好具有7个元素的char数组,六个字符加\\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. C中的字符串是设置长度的,因此您不能在其中附加任何内容。 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). 您只有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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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