_BLOCK_TYPE_IS_VALID(pHead->nBlockUse) Exception

来源:互联网 发布:c语言打印double 编辑:程序博客网 时间:2024/05/20 02:26
Author: YuManZi
Date: 2014/06/11


when encountering _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) exception, in most cases it is caused by a second delete of a pointer. See the following example first.


void Container::AddConfToTemp(const string & i_title, const int * i_authors, const int & i_authorCount,
const int & i_conf, const int & i_year) {
Publication pub = new Publication();
pub->Initialize(i_title, i_authors, i_authorCount, i_conf, i_year);
tempPubSet.push_back(pub);
}

In the above piece of codes, Publication is a class containing a pointer. So the destructor of Publication will delete the pointer.
Each call of function AddConfToTemp, a Publication object pub will be created by information of parameters, followed by adding pub into an STL container 
tempPubSet. At the end of the function, the life cycle of pub comes to an end, which means destructor of Publication will be called to delete the pointer in pub. (Note that other data are still available,except the pointer.) Time comes to the end of life cycle of the container, each elements in the container will auto-call their destructor, and a second delete of the pointer throws the exception.
A alternative way is to insert pointer of Publication into container. And finding a right time to delete these pointers in container.


Publication是一个包含指针的类,因此它的析构函数有delete指针的操作。在这个函数中,一次调用将会用参数传递进来的信息创建一个Publication对象,然后插入tempPubSet这个容器中。当跟踪这个函数发现,当函数结束时,pub的生存周期也结束,因此会自动调用Publication的析构函数(指针无效了,但是其它数据还有效)。而当容器tempPubSet的生存周期结束时,容器中的对象将被释放,在本例中所有的pub将会再次执行析构函数。因此产生了二次delete指针的问题。
解决这一问题的方法是添加Publication的指针进入容器,并在一个恰当的时机将这些指针delete掉。
0 0
原创粉丝点击