Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio 22 - Diagnostic Tools - Memory Usage not showing memory leak

I want to detect a simple memory leak using Visual Studio 22. I am using C++.


#include <iostream>

void leak(const unsigned numBytesToLeak)
{
    new char[numBytesToLeak];
}

int main()
{
    std::cout << "before" << std::endl; // breakpoint 1
    leak(646497);
    std::cout << "after" << std::endl; // breakpoint 2
}

I am using the Debug build with optimizations set to /Od (off).


I set two breakpoints around the line that causes the leak. I am running debugger and taking snapshots of my heap before and after the leak. What I think I should be seeing is an increase of the heap when I hit the second breakpoint. But I do not.

Screenshot of Visual Studio. Shows my source code and Diagnostics Tools window. The Memory Usage view in the Diagnostics window shows that my heap size did not increase despite the code allocating memory on the heap using the keyword new.


Why is my memory leak not being detected?

like image 688
Vader Avatar asked Oct 16 '25 07:10

Vader


1 Answers

Looking at the assembly when the program is compiled with /std:c++20 /W4 /O2 shows that the program indeed will leak, so the leak is not optimized away:

numBytesToLeak$ = 8
void leak(unsigned int) PROC                             ; leak, COMDAT
        mov     ecx, ecx
        jmp     void * operator new[](unsigned __int64)  ; operator new[]
void leak(unsigned int) ENDP                            ; leak

main    PROC                                            ; COMDAT
$LN6:
        sub     rsp, 40                                 ; 00000028H
        mov     ecx, 646497                             ; 0009dd61H
        call    void * operator new[](unsigned __int64) ; operator new[]
        xor     eax, eax
        add     rsp, 40                                 ; 00000028H
        ret     0
main    ENDP

However, VS2022 does not report this as a problem. Not even compiled with /fsanitize=address (which catches the leak in g++ and clang++ if compiled unoptimized) will it report the leak.

You'll most likely have to wait untill enough people have requested /fsanitize=leak to be added to Visual Studio too until such leaks will be caught.

like image 85
Ted Lyngmo Avatar answered Oct 18 '25 23:10

Ted Lyngmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!