我有一张地图,其中键值是2维指针的地址,值是关于图像的一些元数据。
当我在分配和释放函数上运行valgrind时,valgrind显示无效的4错误读取。
struct MemType
{
// Store the data type of the pointer
int dataType;
int noOfRows;
int noOfColumns;
int noOfItems;
};
map < unsigned long, MemType > _MemHandle2DPointer;
short** AllocateMemory(int rowSize, int columnSize)
{
short** ptr2D = new short*[rowSize];
for (unsigned int i = 0; i < rowSize; i++)
{
ptr2D[i] = new short[columnSize];
//Initialize the memory
for(unsigned int j = 0; j < columnSize; j++)
{
ptr2D[i][j] = 0;
}
}
// Assign type id and add to the list of 2D pointers
MemType mem2DType;
mem2DType.dataType = 0;
// Store the number of rows and columns
mem2DType.noOfRows = rowSize;
mem2DType.noOfColumns = columnSize;
mem2DType.noOfItems = 0;
// Insert the pointer into the map
_MemHandle2DPointer[(long) ptr2D] = mem2DType;
return ptr2D;
}
void ReleaseMemory (short** ptr2D)
{
// Releasing memory occupied by 2D pointer
if (ptr2D != NULL)
{
map < unsigned long, MemType >::iterator iter = _MemHandle2DPointer.find((long)ptr2D);
if (iter != _MemHandle2DPointer.end())
{
//cout<<" Releasing Memory occupied by 2D pointer \n";
_MemHandle2DPointer.erase((long)ptr2D);
for (unsigned int i = 0; i < iter->second.noOfRows; i++)
{
delete [] (short *) ptr2D[i];
}
delete [] (short **) ptr2D;
ptr2D = NULL;
}
}
}
int main()
{
short** dminImage = AllocateMemory(100,200);
ReleaseMemory (dminImage);
return 0;
}
我通过此解决方法解决了这个问题。
void ReleaseMemory(短** ptr2D) {
// Releasing memory occupied by 2D pointer
if (ptr2D != NULL)
{
map < unsigned long, MemType >::iterator iter = _MemHandle2DPointer.find((long)ptr2D);
if (iter != _MemHandle2DPointer.end())
{
//cout<<" Releasing Memory occupied by 2D pointer \n";
// _MemHandle2DPointer.erase((long)ptr2D);
for (unsigned int i = 0; i < iter->second.noOfRows; i++)
{
delete [] (short *) ptr2D[i];
}
_MemHandle2DPointer.erase((long)ptr2D);
delete [] (short **) ptr2D;
ptr2D = NULL;
}
}
}
我对导致早期错误的原因感到困惑。 没有规定使用智能指针或任何c ++ 11 stuff.it是遗留代码。
答案 0 :(得分:1)
您正在删除具有迭代器的map元素,然后仍然使用迭代器。不要那样做。迭代器通过擦除它指向的元素而失效。