#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:
1546-503 End of allocated object 0x2001D9F0 was overwritten at 0x2001DA54.
1546-514 The first eight bytes of the object (in hex) are: 6161616161616161.
1546-519 This object was (re)allocated at line 10 in _debug_realloc.c.
_debug_umalloc + D0
_debug_umalloc_init + 3C
_debug_malloc + 5C
main + 28
1546-512 Heap state was valid at line 10 in _debug_realloc.c.
_int_debug_umalloc + 54
_debug_umalloc + D0
_debug_umalloc_init + 3C
_debug_malloc + 5C
main + 28
1546-511 Heap error detected at line 14 in _debug_realloc.c.
1546-522 Traceback:
d0c017a4 = _debug_memset + 0x50
100003ec = main + 0x78