-
Pointers
ok i want to make a function and use a pointer and make it in free store part of the memory like this:
#include <iostream.h>
void hi();
int main ()
{
cout<<"hi"<<endl;
hi();
cout<<pAge<<endl;
/* it doesnt remember pAge when it should be in the free store part of memory which means it should stay in memory right ? */
}
void hi()
{
int * pAge = new short int;
*pAge = 6;
}
why is pAge deleted from memory when i put it in free store where it shouldnt be deleted ?
-
That is because of your function:
PHP Code:
void hi()
{
int * pAge = new short int;
*pAge = 6;
}
You are trying to reinitialize the pointer as a new integer inside the function and the function will delete the pointer as soon as it's returned. So you have nothing left in the point after you call the function.
A working approach would be like this:
PHP Code:
#include <iostream.h>
void hi();
int main ()
{
int * pAge = new short int; //initialize the pointer outside the function
cout<<"hi"<<endl;
hi();
cout<<pAge<<endl;
/* it doesnt remember pAge when it should be in the free store part of memory which means it should stay in memory right ? */
}
void hi()
{
//just set the pointer's value
*pAge = 6;
}
-
ok now I see what was wrong. Thanks for the reply.
-
It doesn't free the memory, it just forgets the pointer. You've created a fine memory leak here...
BTW, abdul's code won't work either because the identifier pAge is local to the function main and can't be used in hi.
-
And note that you should be using the Standard C++ Library headers (i.e. <iostream> not <iostream.h>).
And yes, the campaign starts here :D