_debug_heapmin — Free unused memory in the default heap

Format

#include <stdlib.h>  /* also in <malloc.h> */
int _debug_heapmin(const char *file, size_t line);

Purpose

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.

Return values

If successful, returns 0; otherwise, returns -1.

Examples

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;
}

Possible output is:

Header information of object 0x000738b0 was overwritten at 0x000738ac.
The first eight bytes of the memory block (in hex) are: AAAAAAAAAAAAAAAA.
This memory block was (re)allocated at line number 13 in _debug_heapmin.c.
Heap state was valid at line 14 of _debug_heapmin.c.
Memory error detected at line 17 of _debug_heapmin.c.