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.
Why is my memory leak not being detected?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With