简体   繁体   English

尝试使用指针将一个字符串复制到另一个字符串时检测到堆栈崩溃

[英]Stack smashing detected when trying to copy one string to another using pointers

I am trying to copy one string to another using pointers, but stack smashing error occurred, while the string is copied successfully. 我正在尝试使用指针将一个字符串复制到另一个字符串,但是在成功复制字符串的同时发生了堆栈粉碎错误。

Here's the code below, 这是下面的代码,

#include <stdio.h>
void strcat(char *str1, char *str2) {
    char *run = str1;
    while(*run !='\0')
        run++;
    while(*str2 !='\0') {
        *run = *str2;
        run++;
        str2++;
    }
    *run = '\0';
}
int main() {
    char s[] = "hellomojo";
    char t[] = "world";

    printf("\ns :%s", s);
    printf("\n t :%s",t);
    strcat(s, t);
    printf("\ns after:%s",s);
}

Is it due to illegal access to memory not pointed by pointers? 是由于非法访问未由指针指向的内存吗?

This char s[]="hellomojo"; 这个char s[]="hellomojo"; is basically the same as char s[10]="hellomojo"; char s[10]="hellomojo";基本相同char s[10]="hellomojo"; . It is an array of 10 characters (including the NUL-terminator). 它是一个10个字符的数组(包括NUL终止符)。 You cannot store more than 10 characters in it. 您最多可以存储10个字符。 But you concatenate the other string with this, writing into illegal memory locations beyond the array. 但是,您将其他字符串与此连接在一起,从而将其写入数组之外的非法内存位置。 This invokes Undefined Behaviour . 这将调用未定义行为 Hence the stack smashing problem. 因此,堆栈粉碎问题。

The fix would be to increase the size of the first array like: 解决方法是增加第一个数组的大小,例如:

char s[32] = "hellomojo"; /* 32 chosen arbitrary */

Working with what little code was supplied, my guess would be that at least one of those char pointers doesn't have enough allocated memory, or does not have a null terminating character as expected. 使用提供的代码很少,我猜想那些字符指针中至少有一个没有足够的分配内存,或者没有预期的空终止符。

You show the code, but what is the output and the error message? 您显示代码,但是输出和错误消息是什么? With more information, it would be easier to debug. 有了更多信息,调试起来会更容易。

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

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