I am currently studying C++ from a textbook, and according to the author, this code does not cause a memory leak, despite the fact that when I asked ChatGPT, which told me otherwise. The code is simple and is the following:
#include<iostream>
void FuncOne() {
// this is created on the free store?
// even after the function is finished, the memory is still there.. (I assume)
int* pVar = new int(5);
std::cout << "the value of *pVar is:" << *pVar;
}
int main() {
FuncOne();
std::system("pause");
return 0;
}
*pVar
should cause a memory leak since there is no delete
on it? Could perhaps someone explain to me if there is something that I am missing or if it's a simple mistake from the author?
Any explanation would be much appreciated!
The compiler can optimize out the statement int* pVar = new int(5);
applying the as-if rule and producing the resulting function
void FuncOne() {
cout << "the value of *pVar is:" << 5;
}
That does not have a memory leak: https://godbolt.org/z/38TfqaPfc
If you disable the optimization, it leaks https://godbolt.org/z/8ojhjdP4q:
=================================================================
==1==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 4 byte(s) in 1 object(s) allocated from:
#0 0x7fcf8c2f9518 in operator new(unsigned long) (/opt/compiler-explorer/gcc-13.2.0/lib64/libasan.so.8+0xdb518) (BuildId: 5ce9c09d3612315d01d50bcaafaea176e7ddab77)
#1 0x4011e1 in FuncOne() /app/example.cpp:10
#2 0x4011be in main /app/example.cpp:5
#3 0x7fcf8bc29d8f (/lib/x86_64-linux-gnu/libc.so.6+0x29d8f) (BuildId: a43bfc8428df6623cd498c9c0caeb91aec9be4f9)
SUMMARY: AddressSanitizer: 4 byte(s) leaked in 1 allocation(s).
But technically, the program has a memory leak - the code allocates and does not delete a resource, you should not rely on optimizations and expect that they fix memory leaks.