HEAP CORRUPTION DETECTED: after Normal block (#131) at 0x00827A68.

Hi ,

I have created below String class and same called from Main function. When I execute main function, end of the execution in String class destructor while executing "delete []chp; ". I see heap corruption error.
#include "stdafx.h"
class string1
{
private:
char* chp;
int len;
public:
string1():chp(NULL),len(0)
{ }
//constructor
string1(const char* a)
{
len = 0;
// find the length of string
while (a[len] != '\0')
len++;
//allocate space for string
chp=new char(len+1);
//copy the string
for(int i=0; i<len; i++)
chp[i]=a[i];
}
//copy constructor
string1(string1& b)
{
int len = b.len;
if (len=0)
chp =NULL;
else
{
chp = new char(b.len);
//copy the string
for(int i=0; i<b.len; i++)
chp[i]=b.chp[i];
}
}

~string1()
{

if (len > 0)
delete[] chp;

chp=NULL;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
string1 a="aps";
return 0;
}

The heap corruption message come with below contents
---------------------------
Microsoft Visual C++ Debug Library
---------------------------
Debug Error!

Program: E:\Chandra\C++_Practice\String\String\Debug\String.exe

HEAP CORRUPTION DETECTED: after Normal block (#131) at 0x00827A68.
CRT detected that the application wrote to memory after end of heap buffer.


(Press Retry to debug the application)
---------------------------
Abort Retry Ignore
---------------------------

Please help on on resolving above error.
Firstly, you should enclose your code inside code tags.

You are intending to declare a pointer to a char array but you are instead creating a pointer to a char. In both your constructor and copy constructor, you should create the pointer to the char array as follows:

 
chp = new char[len+1];


I also suggest that you put a null terminator at the end:

1
2
3
for(int i=0; i<len; i++)
   chp[i] = a[i];
chp[len] = '\0';


HTH
You are also assigning in your if statement when I suspect you wanted a comparison

if (len=0)

should probably be:

if (len == 0)
Hi Ajh32,

Thanks for correcting me. After implementing your suggestion that is declare a pointer to a char array as shown below, the issue has been resolved.

chp = new char[len+1];

I didn't notice the difference between chp=new char(len+1); and chp = new char[len+1]; lines.


Hi Lodger,
Thanks for correcting coding error.

Hi Ajh32,

Thanks for correcting me. After implementing your suggestion that is declare a pointer to a char array as shown below, the issue has been resolved.

chp = new char[len+1];

I didn't notice the difference between chp=new char(len+1); and chp = new char[len+1]; lines.


Good to hear.

Did you make the code change in the copy constructor as well, plus put the null terminator at the end of the array as suggested?
Yes, I did. Thanks again.
Topic archived. No new replies allowed.