Search code examples
cwindowsvisual-c++visual-studio-2019

Using Address Sanitizer and _CrtDumpMemoryLeaks() with MSVC


I'm having an issue with compiling with both /fsanitize=address and /MDd compiler options.

#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#else
#include <stdlib.h>
#endif

#include <stdio.h>

int main(int argc, char **argv) {
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
    _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);

    int *foo = malloc(sizeof(*foo) * 1024);
    printf("%d\n", _CrtDumpMemoryLeaks());

    return EXIT_SUCCESS;
}

With cl test.c /MDd /Zi works as expected and reports the leak.

Detected memory leaks!
Dumping objects ->
test.c(20) : {104} normal block at 0x000001ABE8BFA130, 4096 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
1

However, adding address sanitizer, cl test.c /fsanitize=address /MDd /Zi reports no leaks.

0

I had assumed according to MSDN that this might work.


Solution

  • Thank you to the commenter for pointing out that even if they did work together, you'd expect that _CrtDumpMemoryLeaks() would always report a leak because:

    The AddressSanitizer runtime doesn't release memory back to the OS during execution. From the OS's point of view, it may look like there's a memory leak. This design decision is intentional, so as not to allocate all the required memory up front.

    I still am not quite sure I'm not seeing this behavior though and _CrtDumpMemoryLeaks() is resulting in 0 when /fsanitize=address is enabled.

    However, this clears up the issue for me, and I should just expect to create different builds to test either with address sanitizer or _CrtDumpMemoryLeaks().