#include <stdlib.h> /* also in <malloc.h> */
int _debug_heapmin(const char *file, size_t line);
This is the debug version of _heapmin. Like _heapmin, it returns all unused memory from the default runtime heap to the operating system. In addition, _debug_heapmin makes an implicit call to _heap_check, and stores the file name file and the line number line where the memory is returned.
If successful, returns 0; otherwise, returns -1.
This example allocates 10000 bytes of storage, changes the storage size to 10 bytes, and then uses _debug_heapmin to return the unused memory to the operating system. The program then attempts to overwrite memory that was not allocated. When _debug_heapmin is called again, _heap_check detects the error, generates several messages, and stops the program.
/* _debug_heapmin.c */
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *ptr;
/* Allocate a large object from the system */
if (NULL == (ptr = (char*)malloc(100000))) {
puts("Could not allocate memory block.");
exit(EXIT_FAILURE);
}
ptr = (char*)realloc(ptr, 10);
_heapmin(); /* No allocation problems to detect */
*(ptr - 1) = 'a'; /* Overwrite memory that was not allocated */
_heapmin(); /* This call to _heapmin invokes _heap_check */
puts("_debug_heapmin did not detect that a non-allocated memory block"
"was overwritten.");
return 0;
}
The output is similar to:
1546-510 Header information of object 0x200360E0 was overwritten at 0x200360DC.
1546-514 The first eight bytes of the object (in hex) are: 4300000000000000.
1546-519 This object was (re)allocated at line 14 in _debug_heapmin.c.
_debug_urealloc + 128
_debug_realloc + 18
main + 6C
1546-512 Heap state was valid at line 15 in _debug_heapmin.c.
_debug_uheapmin + 50
_debug_heapmin + 54
main + 80
1546-511 Heap error detected at line 18 in _debug_heapmin.c.
1546-522 Traceback:
d119522c = _debug_uheapmin + 0x58
d0c010d0 = _debug_heapmin + 0x5C
10000418 = main + 0xA4