Re: is delete[] necessary?
On Jan 26, 11:47 pm, peter koch <peter.koch.lar...@gmail.com> wrote:
On 26 Jan., 23:24, "John Brawley" <jgbraw...@charter.net> wrote:
Please;
Given something like:
main() {
int * label = new int[123456789];
for(;;)
if ( /* somecondition == true */) { goto end; }
/* do something sane for a long time*/
end:
delete[] label; // is this _necessary_ in this case?
return 0;
}
IOW, if the array[] is used right up until the program
terminates, is it necessary to delete the array[]? (Does a
terminated C++ program 'leave anything behind' that affects
the machine? Doesn't termination of a program release any
memory that was associated with it?)
This is not a C++ question, but from the point of view of C++
you do have a memory leak.
It depends on your definition of memory leak. From a purely C++
point of view, the world ceases to exist when the program
terminates, the question has no meaning.
While some operating systems do free some resources allocated
by processes, not all operating systems do so, and most (if
not all) operating systems don't release all resources
acquired by a process.
This is true up to a point, but the number of resources not
covered is generally very, very small (e.g. temporary
files---good OS's might recover them, but neither Unix nor
Windows does). And you need to provide a mechanism for
recovering such resources anyway, because for better or worse,
there will be times when the program terminates without freeing
them.
If you program on any kind of "standard" operating system, the
leak will not propagate. On a sidenote, prefer std::vector
for new [].
I'd consider that more than a sidenote. Just use std::vector,
and the question doesn't arise. Including if you later wrap the
code in a function, and call it several times. With some of the
"something sane" occasionally throwing an exception.
The basic rule is to write clean, neat code, which works
regardless of the context where it is used, and which works even
if there are exceptions, etc. The question of whether the OS
will recover resources on program termination is one that you
should only ask at the system level---do I have to provide some
additional means to release this resource, e.g. in case of
abnormal termination, or will the system take care of it.
The one exception, of course, is static data, such as
singletons. If you define a singleton, its context is "fixed",
in some ways. In such cases, your main worry is that it will be
there when needed, which generally leads to *not* deleting it on
program shutdown.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34