All calls to heap functions such as malloc, free, calloc, realloc, new, and delete resolve to Debug versions of those functions that operate in the debug heap. When you free a memory block, the debug heap automatically checks the integrity of the buffers on either side of your allocated area and issues an error report if overwriting has occurred.
The _crtDbgFlag flag contains these bit fields:
Bit field | Description |
---|---|
_CRTDBG_ALLOC_MEM_DF | ON (default): Turns on debug allocation.
OFF: Allocations remain chained together but their block type is _IGNORE_BLOCK. |
_CRTDBG_DELAY_FREE_MEM_DF | ON: Prevents memory from actually being freed, as for simulating low-memory conditions.
OFF (default): Keeps freed blocks in the debug heap's linked list but marks them as _FREE_BLOCK and fills them with a special byte value. |
_CRTDBG_CHECK_ALWAYS_DF | ON: Causes _CrtCheckMemory to be called at every allocation and deallocation. This slows execution, but catches errors quickly.
OFF (default): Does not call _CrtCheckMemory. |
_CRTDBG_CHECK_CRT_DF | ON: Causes blocks marked as type _CRT_BLOCK to be included in leak-detection and state-difference operations. When this bit is off, the memory used internally by the run-time library is ignored during such operations.
OFF (default): Does not include _CRT_BLOCK blocks in leak-detection and state-difference operations. |
_CRTDBG_LEAK_CHECK_DF | ON: Causes leak checking to be performed at program exit via a call to _CrtDumpMemoryLeaks. An error report is generated if the application has failed to free all the memory that it allocated.
OFF (default): Does not perform leak checking at program exit. |
To change one or more _crtDbgFlag bit fields and create a new state for the flag.
newFlag
parameter set to _CRTDBG_REPORT_FLAG (to obtain the current _crtDbgFlag state) and store the returned value in a temporary variable.
newFlag
parameter set to the value stored in the temporary variable to create the new state for _crtDbgFlag. For example, the following lines of code turn on automatic leak detection and turn off checking for blocks of type _CRT_BLOCK:
// Get current flag int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); // Turn on leak-checking bit tmpFlag |= _CRTDBG_LEAK_CHECK_DF; // Turn off CRT block checking bit tmpFlag &= ~_CRTDBG_CHECK_CRT_DF; // Set flag to the new value _CrtSetDbgFlag( tmpFlag );