memory_manager.exe 中 0x00423e3b 处未处理的异常:0xC0000005: 访问冲突读取位置 0x00000004。
源文件下载:http://www.cppblog.com/Files/mymsdn/memory_manager_bug_vs2008_debug.zip 嘿,
我正在尝试创建一个内存管理器函数来解决一些问题:
- 在分配内存时引用计数新的/删除的计数器 分析内存泄漏问题。
- 减少内存碎片。
我已经编写了 memory_manager 类来管理分配和 释放一 block 内存。 界面:
void *allocate(size_t size);
BOOL deallocate(void * ptr);
// ...
我正在尝试创建一个新的展示位置来替换来自 系统,所以我添加下面的代码来做到这一点。
#ifdef _DEBUG
static memory_manager mm;
inline void * __cdecl operator new(unsigned int size,
const char *file, int line)
{
void * res;
if((res = mm.allocate(size)) == 0)
{
// go to default allocator
}
return res;
};
inline void __cdecl operator delete(void *p)
{
if(!mm.deallocate(p))
return;
};
inline void __cdecl operator delete[]( void * p )
{
if(!mm.deallocate(p))
return;
};
#endif
#ifdef _DEBUG
#define DEBUG_NEW new(__FILE__, __LINE__)
#else
#define DEBUG_NEW new
#endif
#define new DEBUG_NEW
但是我在运行时遇到了异常,“Unhandled exception at memory_manager.exe 中的 0x00423e3b:0xC0000005:读取访问冲突 位置 0x00000004。”。
我的 memory_manager 代码使用了 STL 代码来管理我的管理器 结构。
我调试我的代码并进入STL代码,我发现它使用了CRT malloc 分配内存,解构静态变量后 “memory_manager mm”,系统抛出未处理的异常。
问题:
我不知道如何改进我的代码以使用 placement new/replace 我的代码的新功能?
我不知道解构静态变量发生了什么?
我不知道有什么更好的方法来解决我在 这篇文章的开头?
我正在考虑创建一个 shared_ptr 来处理它,可能是 像这样:
shared_ptr sp_(new MyClass);
// inner of shared_ptr:
// 1. new MyClass use the system allocator to assign memory.
// 2. In the constructor of the shared_ptr:
// 2.1 copy the memroy of the (new MyClass) object into our memory:
// static memory_manager mm;
// void * p = mm.allocate(sizeof obj);
// memmove( from obj to p);
// delete obj;
// return p;
// 3. Is it right?
// 4. if it's a array, like new MyClass[10]; we must delete the object
像这样删除 [] obj 吗?怎么区分呢?
谢谢!
最佳答案
问题是您在 memory_manager_main.cpp
中重载了全局 operator delete
和 operator delete[]
。作为一般准则,如果重载 new
或 delete
运算符之一,您很可能必须为所有运算符实现重载。
然后在内存管理器类内部使用 std::map
和 std::multimap
,它们都依赖于 std::allocator
类,除非您另有说明。这至少对于 Microsoft 随 Visual Studio 提供的版本而言,依赖于 operator delete
/operator new
进行释放和分配。
我不确定,但您可能最终使用错误的删除删除内容,或者您尝试在 std::map
的析构函数中使用 operator delete 删除内容operator delete
,它依赖于您要删除的类的实例?
您可以使用 malloc
/free
实现您自己的分配器来解决这个问题。
关于c++ - 如何自己管理内存? memory_manager.exe : 0xC0000005: Access violation reading location 0x00000004 中 0x00423e3b 处未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3200816/