PDA

View Full Version : scope of dynamic variabe after program termination



babu198649
6th February 2008, 11:57
hi
a variable is allocated in dynamic memory(using new and is not deleted) and the programs gets terminated .now does the memory allocated will become junk.


int main()
{
int *i = new int;
}

if the above program is executed it just allocates 4 bytes in heap and the program gets terminated.

does this allocated memory will never be free even after program termination.because the books say that the newed variables can made free only with delete.

also,

if a variable is newed twice then will the memory be allocated twice.


#include <iostream.h>
int main()
{
int *i;
i = new int; //newed first time
cout<<&*i<<" ";
i= new int; //newed second time
cout<<&*i;
}

in the above code the variable i is newed twice and the address of newed location is different on both allocations.

how to find a variable is already newed or not.

jpn
6th February 2008, 12:06
does this allocated memory will never be free even after program termination.because the books say that the newed variables can made free only with delete.
OS will free the memory after program execution stops but image what happens if one does this constantly during the program execution.


how to find a variable is already newed or not.
A common approach is to initialize pointers to null and set them back to null after deletion.

babu198649
6th February 2008, 12:20
thanks jpn


A common approach is to initialize pointers to null and set them back to null after deletion.

what if a pointer takes the first value(NULL) in the heap while allocating a space for it

wysota
6th February 2008, 13:09
It can't. The heap starts with much higher addresses.