Re: HeapAlloc on Vista
John wrote:
Hi,
Has anyone experienced odd behavior with the win32 heap functions on
Vista? We are having a problem where HeapAlloc is returning the same
pointer value in two calls, before the first call is freed. This only
happens in Vista.
The documentation for HeapFree states:
Calling HeapFree twice with the same pointer can cause heap corruption,
resulting in subsequent calls to HeapAlloc returning the same pointer
twice.
But the application only calls HeapFree inside the following function:
void FreeMem(void*& p)
{
__try
{
if (p != NULL) HeapFree(hHeap, 0, p);
}
__finally
{
p = NULL;
}
}
That function provides false safety. For a start, if you are deleting an
int*, you do:
int* p;
....
FreeMem(p); //compiles on non-standard compilers like VC6
assert(p == 0); //this assert will fire!
The problem is that you are passing a temporary void* pointer to the
function, and 0ing that pointer has no effect on p. Lets say you get
around this problem by modifying FreeMem:
template <class T>
void FreeMem(T*& p)
{
__try
{
if (p != NULL) HeapFree(hHeap, 0, p);
}
__finally
{
p = NULL;
}
}
Now, you can bind directly to the passed pointer, so at least
assert(p==0);
won't fire. But this still hides the fundamental problem with any kind
of pointer-nulling memory management:
int* p;
....
int* q = p;
FreeMem(p);
FreeMem(q); //boom
Safe memory management is not too difficult in C++, but it relies on
idioms such as smart pointers and RAII, not on functions like your
FreeMem one. I suspect your problem is simply heap corruption...
Tom