下面的代码给我错误***堆栈粉碎被检测到的***:

Below code gives me error *** stack smashing detected ***:

本文关键字:检测 代码 错误 堆栈      更新时间:2023-10-16

任何人都可以告诉代码中的问题是什么?它为我提供了正确的输出,但最后我收到错误。

我使用GDB检查我在末尾获得信号为

__ stack_chk_fail()在stack_chk_fail.c:2828 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数组的B数组,因此固定了分配给堆栈中数组B的内存。如果要避免这种情况,请使char数组足够大,以添加到或尝试使用std :: string并与此链接中的提示相连。如何在C 中加入两个字符串?

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