|
From: Tom H. <to...@co...> - 2006-06-19 19:41:42
|
In message <200...@co...>
Verdi March <ver...@co...> wrote:
> On Tuesday 20 June 2006 00:38, Tom Hughes wrote:
>
> > The only pointer to that memory is "ip" and once you return from
> > main that variables goes out of scope and you no longer have any
> > valid pointers to the memory.
>
> I see. But when main() returns, the program will terminate and the
> memory being used will be released anyway. The reason I was hoping
> this being a case of "reachable" is that often I don't explicitly
> free() pointers which will be used until a program terminates.
It is true that it is more of a technical leak (although maybe not
in a multithreaded program) but a static variable is better if you
really want a lifetime that matches that of the program.
> Just for curiosity, I changed the program to "exit(0)" instead
> of "return 0", and valgrind now reports "unreachable" instead
> of "definite lost". Does it mean that I should always use "exit"
> to terminate programs? I thought that in main(), both "return" and
> "exit" achieve the same effect.
Both are fine - the difference is that return exits main, unwinding
the stack into the caller of main and in doing so valgrind will mark
that stack frame as invalid. Eventually the run time system (the
function which wraps main) will call the exit system call and the
process will die.
When you call exit() you leave the main() frame on the stack and
enter the exit() function which never returns - instead it calls
the exit system call and the process dies.
That is why your variable (which is part of main's stack frame) is
invalid in one case and valid in the other.
Tom
--
Tom Hughes (to...@co...)
http://www.compton.nu/
|