#include <stdlib.h> /* also in <malloc.h> */ void *_debug_realloc(void *ptr, size_t size, const char *file, size_t line);
This is the debug version of realloc. Like realloc, it reallocates the block of memory pointed to by ptr to a new size, specified in bytes. It also sets any new memory it allocates to 0xAA, so you can easily locate instances where your program tries to use the data in that memory without initializing it first. In addition, _debug_realloc makes an implicit call to _heap_check, and stores the file name file and the line number line where the storage is reallocated.
If ptr is NULL, _debug_realloc behaves like _debug_malloc (or malloc) and allocates the block of memory.
Because _debug_realloc always checks to determine the heap from which the memory was allocated, you can use _debug_realloc to reallocate memory blocks allocated by the regular or debug versions of the memory management functions. However, if the memory was not allocated by the memory management functions, or was previously freed, _debug_realloc generates an error message and the program ends.
Returns a pointer to the reallocated memory block. The ptr argument is not the same as the return value; _debug_realloc always changes the memory location to help you locate references to the memory that were not freed before the memory was reallocated.
If size is 0, returns NULL. If not enough memory is available to expand the block to the given size, the original block is unchanged and NULL is returned.
This example uses _debug_realloc to allocate 100 bytes of storage. It then attempts to write to storage that was not allocated. When _debug_realloc is called again, _heap_check detects the error, generates several messages, and stops the program.
/* _debug_realloc.c */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char *ptr;
if (NULL == (ptr = (char*)realloc(NULL, 100))) {
puts("Could not allocate memory block.");
exit(EXIT_FAILURE);
}
memset(ptr, 'a', 105); /* overwrites storage that was not allocated */
ptr = (char*)realloc(ptr, 200); /* realloc invokes _heap_check */
puts("_debug_realloc did not detect that a memory block was overwritten." );
return 0;
}
The output is similar to:
End of allocated object 0x00073890 was overwritten at 0x000738f4. The first eight bytes of the memory block (in hex) are: 6161616161616161. This memory block was (re)allocated at line number 8 in _debug_realloc.c. Heap state was valid at line 8 of _debug_realloc.c. Memory error detected at line 13 of _debug_realloc.c.