Hi quick question, say i allocate some memory within a function call, but before the function exits and the pointer to the allocate memory is destroyed, i pass the address of the pointer to a variable declared locally within my program. Will this effect the running of the program in anyway? In other words, would i have any problems in using the local pointer within the main program. For example, this is a program just to illustrate what i mean:
Thanks for your time.
int *LocalPtr = NULL;
LocalPtr = Test();
for(int i=0; i < 99; i++)
cout << LocalPtr[i]; //can i still access the array like this?
delete LocalPtr; //can i still delete the array like this?
int *FuncPtr = new int ;
>>In other words, would i have any problems in using the local pointer within the main program.
No. Your example is the same as simply using LocalPtr = new int ; new returns the pointer. You can do anything you want with it. Also, a more streamlined version of int *Test(void) would be:
You can directly return the value returned from new without needing any kind of local variable in between.
return (new int );
ahhh, that is great! I was just making sure before i carried on developing a class i'm writting. I was kind of thinking that i would not be able to access the data when the function exits, or the os might try and use the memory address of the pointer created within the function. However, this is not the case. Thanks for your help!
>>Will this effect the running of the program in anyway?
Nope, what pointer you use to access anonymous memory doesn't matter as long as you don't delete the memory or lose a pointer to it. Returning the contents of a pointer is just like saying
The memory is still there, it's just referenced by a different name :-)
LocalPtr = FuncPtr;
I suppose then cela, that the os would only try and allocate new memory to that address, as you said, if it had been deleted
>>I suppose then cela, that the os would only try and allocate new memory to that address, as you said, if it had been deleted
If it had been deleted then you'd be playing with a free pointer and probably breaking things :-)