Jack Richards Jack Richards - 3 years ago 274
C++ Question

A LIST_ENTRY has been corrupted (i.e. double remove) at C++

sages of stackoverflow. There is a problem that occures constantly with heap removal in my destructor.The problem is described with A LIST_ENTRY has been corrupted (i.e. double remove) error. But I can't figure out where I am wrong: I allocated some memory in my constructor and,then , freed that memory with my operator

delete[]
in my destructor. No more any kinds of memory removal happen. So what's the problem.
Code:


String():str(NULL), length(0)
{
str=new char [100];
cout<<"Default constructor has been used"<<endl;}
String( const char* ko)
{

str=new char [strlen(ko)];
strcpy(str,ko);
cout<<endl;
length=strlen(ko);
cout<<"The object is initialized"<<endl;
}

String(String &y)
{
length=y.length;
str=new char[length];
strcpy(str,y.str);
cout<<endl;

}


Destructor:


~String ()
{
length=0;
char* spp=str+1;
delete[] str;/*Here is the point of error(btw if get this operator out the code the programm works fine)*/
str=NULL;
cout<<spp;
}

Answer Source

strlen does not include the null terminator, therefore you must add 1 to the amount that you allocate:

str = new char [strlen(ko) + 1];

Without doing this, strcpy() will write off the end of the allocated memory and corrupt whatever is there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download