【问题标题】:Below code gives me error *** stack smashing detected ***:下面的代码给了我错误***检测到堆栈粉碎***:
【发布时间】:2017-09-15 20:44:25
【问题描述】:

谁能告诉我代码中的问题是什么? 它给了我正确的输出,但最后我得到了错误“下面的代码给了我错误*检测到堆栈粉碎*:”4

我用 GDB 来检查我最后得到的信号是

__stack_chk_fail () at stack_chk_fail.c:28 28 stack_chk_fail.c: 没有这样的文件或目录。

#include <iostream>
#include <string.h>
#include <iomanip>

using namespace std;

void computeLps (char p[], int n) {
    int *lps = new int[n];
    int len = 0;
    lps[0] = 0;
    int i = 1;
    while(i < n)
    {
        /* code */
        if(p[len] == p[i]){
            len ++;
            lps[i] = len;
            i++;
        }
        else {
            if(len != 0) {
                len = lps[len - 1];
            }
            else{
                lps[i] = 0;
                i++;
            }
        }
    }

    for (int i = 0; i < n; ++i)
    {
        /* code */
        cout << lps[i]<<" ";
    } 
    cout <<endl;
}

int main() {

    char b[] = "ABABDABACDABABCABAB";
    char a[] = "ABABCABAB";

    strcat (b,"$"); 
    strcat (b,a);

    //cout << b;

    computeLps(b,strlen(b));
    return 0;
}

【问题讨论】:

  • 您在 b 中没有空间来添加任何内容。因此,您的 strcat 调用将覆盖堆栈上分配的其他变量和数据
  • 使用 C++,卢克。打倒string.h!用字符串!
  • 使用 std::string 和 std::vector!

标签: c++ gdb g++ substring


【解决方案1】:

因为你为 b 使用了一个字符数组,所以分配给你的数组 b 在堆栈上的内存是固定的。如果您想避免这种情况,请使 char 数组足够大以添加到或尝试使用 std::string 并与此链接中的提示连接。 How to concatenate two strings in C++?

std::string 将动态分配内存并在需要时增长,如果为其分配的内存已全部使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    相关资源
    最近更新 更多