Unhandled exception at 0x00423e3b in memory_manager.exe: 0xC0000005: Access violation reading location 0x00000004.
Souce file Download: http://www.cppblog.com/Files/mymsdn/memory_manager_bug_vs2008_debug.zip Hey,
I am trying create a memory manager function to resolve some problem:
- reference count the new / delete counter when allocate memory to anaylize the memory leak problem.
- reduce the memory fragment.
I have writen the memory_manager class to manage allocate and deallocate a block of memory. interface:
void *allocate(size_t size);
BOOL deallocate(void * ptr);
// ...
I am trying to create a placement new to replace the new from the system, so I add the code below to do this.
#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
But I encountered the exception in runtime, "Unhandled exception at 0x00423e3b in memory_manager.exe: 0xC0000005: Access violation reading location 0x00000004.".
My memory_manager code has used the STL code to manage my manager structures.
I debug my code and step into the STL code, I found it used the CRT malloc to assign memory, after deconstruct the static variable "memory_manager mm", system throw the unhandled exception.
Questions:
I don't know how to improve my code to use the placement new / replace the new to my code?
I don't know what has happened in deconstruct the static variable?
I don't know is any better way to resolve my problems metion in the begining of this post?
I have a thinking about create a shared_ptr to deal with it, may be like this:
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
like this delete [] obj ? How to difference it?
Thanks!