HEAP CORRUPTION DETECTED:after Normal block
我想自己定义C ++中的字符串类只是为了练习,当定义一个附加函数时,我得到以下错误:
HEAP CORRUPTION DETECTED:普通模块CRT检测到应用程序在堆缓冲区结束后写入内存之后。
当我尝试在“delete [] aPtr”中释放内存时,这个中断就是我的代码:
私人会员:int len,cap; char * aPtr;
String::String() //default constructor
{
len = 0;
cap = 1;
aPtr = new char[1];
aPtr[0] = ' ';
}
String::String(const String &original) //copy constructor
{
if (cap < original.len)
{
char *t;
cap*=2;
len = original.len;
t = new char[cap];
for (int i = 0;i < len + 1;i++) //copy
{
t[i] = original.aPtr[i];
}
delete[] aPtr;
aPtr = t;
}
else
{
len = original.len;
for (int i = 0;i < len + 1;i++) //copy
{
aPtr[i] = original.aPtr[i];
}
}
}
String & String::operator=(const String &original) // = overload
{
if (*this != original) //Check if string = string
{
if (cap < original.len)
{
char *t;
len = original.len;
cap *= 2;
t = new char[cap];
for (int i = 0;i < len + 1;i++) //copy
{
t[i] = original.aPtr[i];
}
delete[] aPtr;
aPtr = t;
}
else
{
len = original.len;
for (int i = 0;i < len + 1;i++) //copy
{
aPtr[i] = original.aPtr[i];
}
}
}
return *this;
}
void String::append(const String &str)
{
char *temp;
int newLen = len + str.len;
if (cap < newLen + 1)
{
cap = 2 * newLen;
temp = new char[cap];
for (int i = 0;i < len;i++)
{
temp[i] = aPtr[i];
}
for (int i = 0; i < str.len + 1;i++)
{
temp[len + i] = str.aPtr[i];
}
delete [] aPtr;
aPtr = temp;
len = newLen;
}
else
{
for (int i = 0; i < str.len + 1;i++)
{
aPtr[len + i] = str.aPtr[i];
}
}
}
任何帮助表示赞赏!
链接地址: http://www.djcxy.com/p/82335.html