【问题标题】:How to delete dynamically allocated pointer to pointer of int in C++?如何在 C++ 中删除动态分配的指向 int 指针的指针?
【发布时间】:2016-03-02 01:11:03
【问题描述】:

我正在尝试删除指向动态分配的整数指针的指针,但是当我关闭程序时出现意外错误。

一、头文件中的声明

class TileMapManager
{
public: 
     //Some public constructor, destructor and some functions...

private:
    // Other private data...
    int m_xSize;
    int m_ySize;
    int **m_mapSlots;

};

下面的分配...

m_mapSlots = new int*[m_ySize];
    for (int i = 0; i < m_xSize; ++i)
        m_mapSlots[i] = new int[m_xSize];

和释放功能。我在析构函数中调用它。

void TileMapManager::ReleaseTilemap(void)
{
    ReleaseTileTexture();

    for (int y = 0; y < m_ySize; ++y)
        delete m_mapSlots[y]; // <- break!

    delete m_mapSlots;  
}

我的程序已在该行触发断点。

我认为删除的方式是好的,但我不知道为什么它会导致问题。 请帮帮我。

【问题讨论】:

  • 不要为 C++ 问题添加 C 标签!它们是不同的语言。
  • m_xSize 在一个循环条件下,m_ySize 在另一个循环条件下。你已经越界了。
  • 对二维数组的不正确仿真的另一个不明智的尝试。

标签: c++ pointers


【解决方案1】:

确定

for (int i = 0; i < m_xSize; ++i)

不应该

for (int i = 0; i < m_ySize; ++i)

?

如果m_xSize &gt; m_ySize 可能会出现未定义的行为,因为

  • m_mapSlots 只指向 m_ySize 指针
  • delete 将尝试释放未分配的内存

【讨论】:

  • 就是我们前几天谈到的。二维循环分配的数组注定要失败:)
【解决方案2】:

永远不要尝试以这种方式模拟二维数组。相反,定义整数的一维向量:

std::vector<int> m_mapSlots;
...
m_mapSlots.resize(m_ySize * m_xSize);

int v = m_MapSlots[x + y * x];

【讨论】:

    【解决方案3】:

    您在分配中使用了错误的变量:

    m_mapSlots = new int*[m_ySize];   //    allocates m_ySize elements
    for (int i = 0; i < m_xSize; ++i) // goes through m_xSize elements
        m_mapSlots[i] = new int[m_xSize];
    

    循环条件中的m_xSize 应该是m_ySize

    或者,你知道,使用 std::vector&lt;int&gt;m_xSize * m_ySize 的大小并避免整个混乱。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-08
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多