【问题标题】:C++ Free Heap block 3da9e0 modified at 3daa08 after it was freedC++ 空闲堆块 3da9e0 在被释放后在 3daa08 处修改
【发布时间】:2014-01-22 13:06:23
【问题描述】:

我在这个网站上看到了一些解决方案,但没有一个能解决我的问题。 我正在实现一个 n-children、不平衡的树类型,并且 add 操作给了我一个例外。 代码如下:

struct Node {
    // Just to initialize the parent node to zero, default constructor
    Node(Node *parent = 0) : m_parent(parent) {
    }

    Node *m_parent;
    vector<Node *> m_children;
    GameBoard m_currentBoard;
};

错误发生的地方:

Node *tempNode = 0;

// Going through each of them to create new nodes
for (unsigned int  i = 0; i < availableBoards.size() ; i++) {
    // Create a new node
    tempNode = new Node;
    tempNode->m_parent = curNode;
    tempNode->m_currentBoard.setBoard(availableBoards[i]);

    // This is the line when program crashes
    curNode->m_children.push_back(tempNode); 
}

我也尝试过在循环中声明 tempNode,但也没有用。

我从 Visual Studio 中检查了手表,curNode 不是 NULL 也不是 tempNode

为什么会出现这个错误?

感谢您的回答。

【问题讨论】:

  • 你确定curNode 是有效的(非空并不意味着有效)?好像已经被释放了
  • 是的,我已经仔细检查过了,我通过参数传递了它。只有它的父字段为空(根节点),但子向量存在,大小为 0。
  • “存在”并不意味着有效。释放内存会将旧数据保留在原来的位置,因此它在调试器中仍然看起来“有效”。

标签: c++ tree heap-memory


【解决方案1】:

好的,问题是在调用第二个代码段之前就破坏了正在运行的对象。是这样的:

class A{
     int *getAsdf();
     int *asdf;
}

int main() {
    A *newObj = new A;
    delete newObj;
    newObj->getAsdf();
}

我对如何从之前删除的对象调用方法一无所知。错误发生在像 getAsdf 这样的函数内部,甚至参数都是有效的。谁能解释一下?

【讨论】:

  • 无效的参数是 this 指针。因为这是一个非虚拟函数,所以函数调用会很好,但是任何对 this 的取消引用都会在无效内存上运行。对 this 指针的任何写入(例如,将 this->asdf 设置为某个值)都可能会损坏内存管理器。
  • 如果我告诉你这是一个写得很糟糕的代码,它会让你感觉好一点吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 2016-04-25
  • 2015-06-15
  • 2011-09-13
  • 2013-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多