我正在尝试将我动态分配的数组释放到删除方法中的structeres指针。我想迭代每个数组字段,它是指向不同结构的指针,删除它然后删除[]整个数组。在第二次迭代中,我有Debug Assertion Failed。这是代码:
void deleting (SimpleStruct **_simpleArrayPtrs, int _iSize)
{
if(0 != _simpleArrayPtrs)
{
for(int i = 0; i < _iSize; ++i)
{
if(0 != _simpleArrayPtrs[i])
{
delete _simpleArrayPtrs[i];
_simpleArrayPtrs[i] = 0;
}
}
delete[] _simpleArrayPtrs;
_simpleArrayPtrs = 0;
cout << "deleting: Memory deallocated" << endl;
}
else
{
cout << "[ERR]deleting: invalid pointer" << endl;
}
}
SimpleStruct** foo(int _iSize)
{
//local size variable
int iSize = _iSize;
SimpleStruct **simpleArrayPtrs = 0;
SimpleStruct *simpleArray = 0 ;
//allocation succeded
if(0!=iSize)
{
// nothrow to avoid exception
simpleArrayPtrs = new (std::nothrow) SimpleStruct*[iSize];
simpleArray = new (std::nothrow) SimpleStruct[iSize];
if(0 != simpleArray && 0 != simpleArrayPtrs)
{
/* initialize random seed: */
srand (time(0));
for(int i = 0; i < iSize; ++i)
{
simpleArrayPtrs[i] = &simpleArray[i];
}
for(int i = 0; i < iSize; ++i)
{
}
}
else
{
cout << "[ERR]foo: alloc failed" << endl;
}
}
else
{
cout << "[ERR]foo: wrong size" << endl;
}
return simpleArrayPtrs;
}
int main()
{
int iSize;
char cCharater;
double time_spent;
clock_t begin, end;
/*********START COUNTING*********/
begin = clock();
FILE* fp = fopen(FILE_NAME, "r");
if (fp == NULL)
{
return -1;
}
fscanf(fp, "%d %c", &iSize, &cCharater);
fclose(fp);
SimpleStruct** simpleStructPtr = foo(iSize);
deleting(simpleStructPtr, iSize);
/*********STOP COUNTING*********/
end = clock();
time_spent = static_cast<double> (end - begin);
cout << "Time spent: " << time_spent << endl;
return 0;
}
答案 0 :(得分:0)
调用delete _simpleArrayPtrs[i]
是错误的。
您不动态分配_simpleArrayPtrs[i]
,因此不应动态解除分配。