gpt4 book ai didi

c++ - 关于C++内存分配和删除的问题

转载 作者:行者123 更新时间:2023-11-30 01:32:28 24 4
gpt4 key购买 nike

我遇到了一个严重的错误。当我在对象层次结构顶部的对象上调用 delete 时(希望导致删除其子对象),我的程序退出并且我得到这个:

*** glibc detected *** /home/mossen/workspace/abbot/Debug/abbot: double free or corruption (out): 0xb7ec2158 ***

followed by what looks like a memory dump of some kind. I've searched for this error and from what I gather it seems to occur when you attempt to delete memory that has already been deleted. Impossible as there's only one place in my code that attempts this delete. Here's the wacky part: it does not occur in debug mode. The code in question:


Terrain::~Terrain()
{
if (heightmap != NULL) // 'heightmap' is a Heightmap*
{
cout << "heightmap& == " << heightmap << endl;
delete heightmap;
}
}

高度图析构函数中的所有内容我都注释掉了,还是这个错误。发生错误时,

heightmap& == 0xb7ec2158

is printed. In debug mode I can step through the code slowly and

heightmap& == 0x00000000

is printed, and there is no error. If I comment out the 'delete heightmap;' line, error never occurs. The destructor above is called from another destructor (separate classes, no virtual destructors or anything like that). The heightmap pointer is new'd in a method like this:


Heightmap* HeightmapLoader::load() // a static method
{
// ....
Heightmap* heightmap = new Heightmap();
// ....other code
return heightmap;
}

会不会与返回一个在静态方法的栈空间中初始化的指针有关?我是否正确执行删除操作?关于我可以检查或做得更好的任何其他提示?

最佳答案

如果从未调用 load() 会发生什么?您的类构造函数是初始化 heightmap,还是在到达析构函数时未初始化?

另外,你说:

... delete memory that has already been deleted. Impossible as there's only one place in my code that attempts this delete.

但是,您没有考虑到您的析构函数在程序执行期间可能被多次调用。

关于c++ - 关于C++内存分配和删除的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1623103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com