Possible Duplicate:
Are memory leaks “undefined behavior” class problem in C++?
Never calling delete
or delete[]
on address returned by new
or new []
resp in a C++ program is an Undefined Behavior or merely a memory leak?
References from the Standard(if any) are welcome.
This came up in one of the comments here & I am just a bit confused about it.
Let's say that if you do not call delete your program will still work. BUT if you do not delete memory allocations your program memory usage will keep growing until your program will run out of free memory (the longer you run it better are the chances for it to happen) which will cause crashes at different points and will be very hard to detect (and I think that whats 'Undefined Behavior' mentioned in the comment means)
The standard is clear with regards to the semantics of
new
anddelete
. There's certainly no undefined behavior if you don't calldelete
; it is, in fact, standard practice for singletons, and I imagine thatstd::cout
andstd::cin
usenew[]
to acquire their buffers (which they almost certainly neverdelete
). Why would not callingdelete
be undefined behavior?What is undefined behavior is calling the wrong form of
delete
, callingfree
for memory allocated withnew
, or in general to attempt to delete an object without following the protocol required by its allocation.It's just a memory leak.
But I explicitly remember the standard saying that use
new
withdelete[]
andnew []
withdelete
is undefined behavior. (or any combination withmalloc
orfree
)I don't think the standard specifically says calling
new
results in undefined behavior if you fail to calldelete
. Also, how can the run-time tell if you calldelete
sometime later or never call it at all?I don't think there are any contracts in the standard that say - if you do X, you MUST do Y afterwards, otherwise it's UB.
[basic.life] (3.8 Object lifetime) in paragraph 4 tells :
If
delete/delete[]
is not called for the objects allocated withnew/new[]
, there would be resource leaks. It could be memory leak if the constructor had allocated dynamic memory. Other things like semaphore lock not released, file handles not released etc can happen if the constructor had allocated them.It will not be undefined behavior.
I dont see how not releasing memory will lead to undefined behaviour. If you dont clean up, the OS still has knowledge of the allocated memory. That will lead to a resource leak for as long as the application runs.