Controlling memory leaks (the failure to properly deallocate memory that was previously allocated), is tightly related to heap management. Unlike stack variables that are automatically deallocated when they are running out of scope, heap objects must be actively deallocated if they are no longer referenced. Leaking large amounts of memory leads to out-of-memory conditions, which in turn results in bad runtime behavior. For this reason, the ability to detect memory leaks during development is indispensable.
Including the DbgNew.h Header File
The object allocator used for NVSG Objects provides automated leak detection in debug mode. To enable this feature, implementation files (*.cpp) must include the DbgNew.h header as the last header file.
// memory leak detection #include "nvutil/DbgNew.h"
When Using Allocation Code Within Header Files
If your application uses allocation code within header files, you need to restrict leak detection to that particular header file. This can be done as follows:
#ifdef _DEBUG # ifndef new # define new new(__FILE__, __LINE__) # define _DEFINED_DBGNEW // restrict the 'new' macro to this header file only # endif #endif // implementation within header utilizing object allocation code // ... #ifdef _DEFINED_DBGNEW # undef new #endif
These statements essentially re-define the 'new' keyword to force the object allocator to track allocations. If you fail to include these statements wherever allocation code is used, you will get an assertion warning you that memory leak detection is bypassed in debug mode.
If the NVSG object allocator detects memory leaks, it outputs the leak warnings to the attached debugger when the NVSG library terminates. A leak warning might look similar to the following line of output:
****Memory Leak Detected*** Source: c:\src\test.cpp, Line: 51, Ptr: 0x0B4D5A80
The output reports the source file and source line where allocation of the leaked memory block took place, and also the memory address of the leaked block.
Leak Detection of Non-NVSG Allocations
This mechanism only tracks allocations performed by the NVSG object allocator nvutil::IAllocator. To track allocations of built-in types or non-NVSG types, refer to the documentation about memory leak detection mechanisms provided by the C-runtime. The C-runtime memory leak detection works in parallel with the memory leak detection provided by the NVSG object allocator.
Back to