Syntax
#include <malloc.h> int _heap_walk(int (*callback_fn)(const void *object, size_t size, int flag, int status, const char* file, int line) );Description
object
_heap_walk calls callback_fn for each object until one of the following occurs:
You may want to code your callback_fn to return a nonzero value if the status of the object is not _HEAPOK. Even if callback_fn returns 0 for an object that is corrupted, _heap_walk cannot continue because of the state of the heap and returns to its caller.
You can use callback_fn to process the information from _heap_walk in various ways. For example, you may want to print the information to a file or use it to generate your own error messages. You can use the information to look for memory leaks and objects incorrectly allocated or freed from the heap. It can be especially useful to call _heap_walk when _heapchk returns an error.
A heap-specific version of this function, _uheap_walk, is also available.
Note:
This example allocates some memory, then uses _heap_walk to walk the heap and pass information about allocated objects to the callback function callback_function. callback_function then checks the information and keeps track of the number of allocated objects.
#include <stdlib.h>#include <stdio.h> #include <malloc.h> int callback_function(const void *pentry, size_t sz, int useflag, int status, const char *filename, size_t line) { if (_HEAPOK != status) { puts("status is not _HEAPOK."); exit(status); } if (_USEDENTRY == useflag) printf("allocated %p %u\n", pentry, sz); else printf("freed %p %u\n", pentry, sz); return 0; } int main(void) { char *p1, *p2, *p3; if (NULL == (p1 = malloc(100)) || NULL == (p2 = malloc(200)) || NULL == (p3 = malloc(300))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } free(p2); puts("usage address size\n----- ------- ----"); _heap_walk(callback_function); free(p1); free(p3); return 0; /**************************************************************************** The output should be similar to : usage address size ----- ------- ---- allocated 73A10 300 allocated 738B0 100 : : freed 73920 224 ****************************************************************************/ }