Malloc Log is an optional extension of the malloc subsystem, enabling the user to obtain information showing the number of active allocations of a given size and stack traceback made by the malloc subsystem. This data can then be used in problem determination and performance analysis.
Malloc Log is not enabled by default, but can be enabled and configured prior to process startup by setting the MALLOCDEBUG environment variable.
Malloc Log records the following data for each malloc or realloc subroutine invocation:
The data is stored into the following global structure:
struct malloc_log * malloc_log_table; #ifndef MALLOC_LOG_STACKDEPTH #define MALLOC_LOG_STACKDEPTH 4 #endif struct malloc_log { size_t size; size_t cnt; uintptr_t callers[MALLOC_LOG_STACKDEPTH]; } size_t malloc_log_size;
The size of the malloc_log structure can change. If the default call-stack depth is greater than 4, the structure will have a larger size. The current size of the malloc_log structure is stored in the globally exported malloc_log_size variable . A user can define the MALLOC_LOG_STACKDEPTH macro to the stack depth that was configured at process start time.
The malloc_log_table can be accessed in the following ways:
#include malloc.h size_t get_malloc_log (void *addr, void *buf, size_t bufsize);This function copies the data from malloc_log_table into the provided buffer. The data can then be accessed without modifying the malloc_log_table. The data represents a snapshot of the malloc log data for that moment of time.
#include malloc.h struct malloc_log * get_malloc_log_live (void *addr);The advantage of this method is that no data needs to be copied, therefore performance suffers less. Disadvantages of this method are that the data referenced is volatile and the data may not encompass the entire malloc subsystem, depending on which malloc algorithm is being used.
To clear all existing data from the malloc log tables, use the reset_malloc_log API as follows:
#include malloc.h void reset_malloc_log(void *addr);
Malloc Log is not enabled by default. To enable Malloc Log with the default settings, set the MALLOCDEBUG environment variable as follows:
MALLOCDEBUG=log
To enable Malloc Log with user-specified configuration options, set the MALLOCDEBUG environment variable as follows:
MALLOCDEBUG=log:records_per_heap:stack_depth
The predefined MALLOCDEBUG configuration options include the following:
The performance of all programs can degrade when Malloc Log is enabled, due to the cost of storing data to memory. Memory usage will also increase.