动态数组分配与回收

mz5052 2015-12-29 12:23:11
下面是一个kmp算法的实现,大家不用管算法的具体思路。现在的问题是程序一直无法出结果,我调试的时候发现卡在kmp_matcher()里面的delete [] next;这条语句。不是很明白为什么会卡在这里,求大神指导。

#include <iostream>
#include <string>
using std::cin; using std::cout; using std::endl;
using std::string;

int* get_next( const string& s );
int kmp_matcher( const string& txt , const string& pat );

int main( void )
{
string txt = "ababcabcacbab";
string pat = "abcac";

int loc = kmp_matcher( txt , pat );

cout << loc << endl;

return 0;
}

int* get_next( const string& s )
{
int N = s.size();
int* next = new int[N];
if( NULL == next )
return NULL;

int i = 0;
int j = -1;
next[ 0 ] = -1;

while( i < N )
{
if( -1 == j || s[ i ] == s[ j ] )
{
++i;
++j;
next[ i ] = j;
}
else
j = next[ j ];
}
return next;
}
int kmp_matcher( const string& txt , const string& pat )
{
int N = txt.size();
int M = pat.size();

if( 0 == N || 0 == M )
return -1;

int* next = get_next( pat );

int i = 0 , j = 0;
while( i < N && j < M )
{
if( txt[ i ] == pat[ j ] )
{ ++i;++j;}
else
j = next[ j ];
}

delete [] next;

if( M == j )
return i - M;
else
return -1;
}
...全文
150 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhouxiaofeng1021 2015-12-29
  • 打赏
  • 举报
回复
int* get_next( const string& s ) { int N = s.size(); int* next = new int[N*2]; //这里改了一下 OK了 if( NULL == next )
zhouxiaofeng1021 2015-12-29
  • 打赏
  • 举报
回复
你的代码写的不符合规范 建议你看看代码编写规范标准 而且很容易出现边界问题 同时呢,你这个int* next = get_next( pat ); 从函数get_next 返回的是 new 还是new[] 这个对于new后的内存地址会有一个内存位置表示是单个还是数组 我调试了下 _RPT3(_CRT_ERROR, "HEAP CORRUPTION DETECTED: after %hs block (#%d) at 0x%p.\n" "CRT detected that the application wrote to memory after end of heap buffer.\n", szBlockUseName[_BLOCK_TYPE(pHead->nBlockUse)], pHead->lRequest, (BYTE *) pbData(pHead)); 到这里 http://blog.csdn.net/wu_lai_314/article/details/8241697 看一下 你这个是内存操作越界问题
张小飞Official 2015-12-29
  • 打赏
  • 举报
回复
这编码风格我也是醉了。。。双层循环注意越界问题!
fly_dragon_fly 2015-12-29
  • 打赏
  • 举报
回复
get_next中 ++i; ++j; next[ i ] = j; 这地方会越界

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧