我试图编写一个代码来找出给定字符串中最长重复子字符串的长度。
代码如下。
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<limits>
#include<iostream>
#include<map>
using namespace std;
class trienode
{
private:
int value;
trienode *child[156];
public:
trienode()
{
value=0;
for(int i=0;i<256;i++)
{
child[i]=NULL;
}
}
void insert(string str,int *,int *);
};
class trie
{
private:
trienode *head;
int max;
public:
trie(string str)
{
head=new trienode();
max=0;
insert(str);
}
void insert(string);
int getmax();
};
void trie::insert(string str)
{
int n=str.length();
for(int i=0;i<n;i++)
{
int result=0;
int set=0;
cout << "inside trie insert" <<str<<endl;
cout << "inside trie insert" <<str.substr(i)<< " " << str<<endl;
cout << "inside trie insert" <<str<<endl;
head->insert(str.substr(i),&set,&result);
cout << "inside trie insert" <<str<<endl;
if(result>max)
max=result;
}
}
void trienode::insert(string str,int *set,int *res)
{
cout << "inside trienode insert" <<endl;
if(str.length()>0)
{
if(str.length()==1)
value=1;
if(child[str.at(0)]!=NULL)
{
*set=1;
child[str.at(0)]=new trienode();
}
else
{
if(!set)
*res++;
child[str.at(0)]->insert(str.substr(1),set,res);
}
}
}
int trie::getmax()
{
return max;
}
int main()
{
//char arr1[]="ATCGATCGA";
trie t("ATCGATCGA");
cout << t.getmax() <<endl;
return 0;
}
当我尝试运行此程序时。抛出了以下运行时错误。我在代码中找不到任何错误。
malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
Aborted (core dumped)
我已经指出了错误的确切位置。
这段代码中出现了错误。
void trie::insert(string str)
{
int n=str.length();
for(int i=0;i<n;i++)
{
int result=0;
int set=0;
cout << "inside trie insert" <<str<<endl;
cout << "inside trie insert" <<str.substr(i)<< " " << str<<endl;
cout << "inside trie insert" <<str<<endl;
head->insert(str.substr(i),&set,&result);
cout << "inside trie insert" <<str<<endl;
if(result>max)
max=result;
}
}
第一个cout cout << "inside trie insert" <<str<<endl;
成功。
第二个cout cout << "inside trie insert" <<str.substr(i)<< " " << str<<endl;
是看到错误的地方。
有些人请帮助我,因为我遇到了这个问题。
谢谢..
答案 0 :(得分:4)
您遇到问题的原因是您已将child
声明为仅包含156
元素的向量,但您在256
循环中最多可访问for
。这会导致很多潜在的未定义行为。