Re: malloc(), realloc(), free in different threads
On Sat, 16 Jun 2007 16:01:00 -0700, maple02
<maple02@discussions.microsoft.com> wrote:
Hi, I'm allocating initial memory in the main UI thread of my application
with malloc().
I then create a worker thread and pass that memory on for its use. The
worker thread will call realloc() if required as the memory requirements grow.
Later, inside my main UI thread, I call free() on the original memory
pointer (which appears to be intact). However, I'm failing an assert in
dbgheap.c at the following line:
* If this ASSERT fails, a bad pointer has been passed in. It may be
* totally bogus, or it may have been allocated from another heap.
* The pointer MUST come from the 'local' heap.
*/
_ASSERTE(_CrtIsValidHeapPointer(pUserData));
Am I violating the rules governing the heap?
It sounds like you're doing this:
void* p = malloc(n); // Main thread
void* q = realloc(p, n2); // Secondary thread
free(p); // Main thread
More than likely, realloc will return a different pointer q and will have
invalidated p. What you need to do is free(q). Note there's no requirement
that the main thread allocate and free memory. The secondary thread could
do it all itself, and typically one thread can free memory allocated by
another. The crucial thing is to compile the code the two threads execute
with the same memory model option, and if split into multiple modules (EXE
and DLLs), use /MD and /MDd for release and debug builds, respectively.
This will cause the modules to link to the same CRT DLL and share the same
heap and most other CRT state.
Note, I ensure the memory is not being used by the thread when I call free().
That's certainly an issue for the user of the memory, but free() couldn't
care less.
--
Doug Harrison
Visual C++ MVP