清除图像地图

clearing a map of images

本文关键字:地图 图像 清除      更新时间:2023-10-16

我有一个地图,其中键值是二维指针的地址,值是有关图像的一些元数据。

当我在分配和释放函数上运行 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 (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];
        }
        _MemHandle2DPointer.erase((long)ptr2D);
        delete [] (short **) ptr2D;
        ptr2D = NULL;
    }       
}

}

我对导致早期错误的原因感到困惑。没有规定使用智能指针或任何 c++ 11 的东西,这是一个遗留代码。

您正在擦除具有迭代器的映射元素,然后仍然使用迭代器。别这样。迭代器通过擦除它指向的元素而失效。