Tuesday, December 28, 2010

Scoping MSVCRT memory tracking flags with scoped_handle

Am just working on some diagnostic extras to be provided as a side-project for Pantheios, with a particular focus on main(). In applying them to some of my system tool programs, I'm finding some false positive memory leaks being reported for FastFormat: this is because FastFormat caches parsed format strings, and they're not released until the library is uninitialised.

I want to "hide" these memory allocations from Visual C++'s CRT memory tracing functionality, and have found a neat little trick for doing so, using STLSoft's scoped_handle, as follows:


#if defined(_DEBUG) && \
    defined(STLSOFT_COMPILER_IS_MSVC)
    int prev = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
    _CrtSetDbgFlag(prev & ~_CRTDBG_ALLOC_MEM_DF);
    stlsoft::scoped_handle scoper(prev, _CrtSetDbgFlag);
#endif

    . . . // allocate memory that wont' be recorded as leaks


  } // MSVCRT settings reset here