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];
}
}
The heap corruption message come with below contents
---------------------------
Microsoft Visual C++ Debug Library
---------------------------
Debug 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 = newchar[len+1];
I also suggest that you put a null terminator at the end: