|
From: Bryan M. <om...@br...> - 2006-06-19 18:46:30
|
Verdi March wrote:
> Hi,
>
> On Tuesday 20 June 2006 00:38, Tom Hughes wrote:
>>> /***********************************/
>>> #include <stdio.h>
>>> #include <stdlib.h>
>>>
>>> int main() {
>>> int *ip;
>>> ip =(int *) malloc(sizeof(int));
>>> return 0;
>>> }
>>> /***********************************/
>> 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.
>
> 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.
>
No - exit your program in the way your program needs to exit.
What you probably don't realise is that there is a lot of code executed
before your function main() is called. Likewise, there is a significant
amount of code executed after your function main() exits before the
program actually exits.
Thus, as Tom says, your only pointer to the memory block goes out of
scope before the program exists and this is a leak.
Bryan "Brain Murders" Meredith
|