无法删除数组(我不知道的错误)

时间:2015-12-06 18:40:30

标签: c++ arrays destructor allocation

我有一个应该在使用时“呼吸”的结构。它是一个指针矩阵。 (BigInt是某种类型,无论它是什么......)

BigInt ***directory;

以这种方式初始化(​​矩阵的大小为M * M):

directory = new BigInt**[M];
for(int i=0;i<M;i++)
    directory[i] = NULL;

并在需要时以这种方式展开:

partition = ...;
directory[partition] = new BigInt*[M];
for(int i=0;i<M;i++)
    directory[partition][i] = NULL;

并以这种方式销毁(此方法从具有BigInt ***目录作为字段的类的析构函数调用):

void del() {
    for(int p=0;p<M;p++)
        if(directory[p]!=NULL) {
            for(int o=0;o<M;o++)
                if(directory[p][o]!=NULL)
                    delete directory[p][o];
        }

    for(int p=0;p<M;p++)
        if(directory[p]!=NULL)
            delete directory[p];

    delete directory;
}

但是,在我的程序结束时,我的程序在dbgheap.c中断(触发断点),位于:

/***
*int _CrtIsValidHeapPointer() - verify pointer is from 'local' heap
*
*Purpose:
*       Verify pointer is not only a valid pointer but also that it is from
*       the 'local' heap. Pointers from another copy of the C runtime (even in the
*       same process) will be caught.
*
*Entry:
*       const void * pUserData     - pointer of interest
*
*Return:
*       TRUE - if valid and from local heap
*       FALSE otherwise
*
*******************************************************************************/
extern "C" _CRTIMP int __cdecl _CrtIsValidHeapPointer(
        const void * pUserData
        )
{
        if (!pUserData)
            return FALSE;

        if (!_CrtIsValidPointer(pHdr(pUserData), sizeof(_CrtMemBlockHeader), FALSE))
            return FALSE;

        return HeapValidate( _crtheap, 0, pHdr(pUserData) );
}

当我尝试通过调用del()或当我尝试删除单个数组(当矩阵为“呼吸”时)尝试释放内存时,会出现相同的断点:

int p = ...;
delete directory[p];

我从来没有发生过这种错误,如果我不释放我的记忆,程序就能正常工作。

1 个答案:

答案 0 :(得分:2)

您正在使用new []分配数组,但使用delete运算符删除它们。如果使用new []分配内容,则应使用delete []删除它,否则会触发未定义的行为。

例如,您应该替换此代码:

delete directory[p];

用这个:

delete[] directory[p];

这同样适用于您发布的代码中的所有其他删除事件。