【发布时间】: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!