|
-
May 3rd, 2002, 03:05 PM
#1
Thread Starter
Lively Member
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 ?
-
May 3rd, 2002, 03:10 PM
#2
PowerPoster
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;
}
-
May 3rd, 2002, 03:13 PM
#3
Thread Starter
Lively Member
ok now I see what was wrong. Thanks for the reply.
-
May 5th, 2002, 05:14 AM
#4
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.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
May 5th, 2002, 05:30 AM
#5
Monday Morning Lunatic
And note that you should be using the Standard C++ Library headers (i.e. <iostream> not <iostream.h>).
And yes, the campaign starts here
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|