下面的代码给我错误***堆栈粉碎检测***:
问题描述:
任何人都可以请告诉代码中的问题是什么? 它给了我正确的输出,但最后我是个得到错误“下面的代码给我错误砸检测*栈*:” 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使用了一个字符数组,所以分配给您的数组b的内存是固定的。如果你想避免这种情况,使char数组足够大,可以添加或尝试使用std :: string并与此链接中的提示连接。 How to concatenate two strings in C++?
std :: string将动态分配内存并在需要时增长,如果为其分配的内存全部使用。
您在b中没有空间添加任何内容。所以你的strcat调用将覆盖堆栈上分配的其他变量和数据。 –
使用C++ Luke。用string.h打倒!用字符串! – user4581301
使用std :: string和std :: vector! – 2017-09-15 22:03:37