C++ Exception4 堆内存溢出。(HEAP CORRUPTION DETECTED)

 

我在构造方法中,对char * c 进行申请内存时,假如 “12345”赋值给 c时,就要申请6块内存,来存储

12345,假如我只申请了 5块内存时,没有为字符串结尾的"\n"也申请一块内存时,在析构函数释放

内存时,就会把出现这种情况;

 

出错的例子:

 

baseString::baseString(const char * c ,int n)
{
    num = n;
    label = new char[std::strlen(c)];   //   出错了, label = new char[std::strlen(c)+1];之后就正确了
    std::strcpy(label,c);
}

 

下面的这个函数,

baseString & baseString::operator=(const char * c)
{
    delete [] label;          //释放内存时,由于 label = new char[std::strlen(c)];  少申请了一个内存,此时释放会释放6块内存,引起堆内存泄露
    num = std::strlen(c);
    label = new char[num+1];
    std::strcpy(label,c);
    return *this;
}

 

posted on 2014-02-23 11:41  fantiejun0436  阅读(143)  评论(0)    收藏  举报

导航