代码如下计算kmp算法中的next[],在DEV-c++中测试时,当字符串str的长度为5时会运行不出来,长度为其他时能正常运行,在在线编译软件中测试时无论str的长度为多少都会出现:memory clobbered past end of allocated block
#include
#include
#include
using namespace std;
void strF(string str, int * f)
{
f [0] = 0;
f [1] = 0;
int k;
int length = str.length();
for(int i = 1; i < length + 1; i++)
{
k = 0;
for(int j = 1; j <= i; j++)
{
if(str.compare(0, j - 1, str, i - j + 1, j - 1) == 0)
{
k = j;
}
}
f [i + 1] = k;
}
}
int * strNext(string str)
{
int * next = new int [str.length() + 1];
int * f = new int [str.length() + 1];
strF(str, f);
next[0] = 0;
next[1] = 0;
int length = str.length();
for(int i = 2; i < length + 1; i++)
{
if(str[i - 1] != str[f[i] - 1])
{
next[i] = f[i];
}
else
next[i] = next [f[i]];
cout<<i<<endl;
}
delete [] f;
return next;
}
int main()
{
string str;
str = "aaaabfdsa";
int * next = new int [str.length() + 1];
next = strNext(str);
int length = str.length();
for(int i = 1; i < length + 1; i++)
cout << next[i] << " ";
cout << endl;
delete [] next;
}

c++ :memory clobbered past end of allocated block
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-