-
returning pointers
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:
Code:
int *Test(void);
int main(void)
{
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?
return 0;
}
int *Test(void)
{
int *FuncPtr = new int [100];
return FuncPtr;
}
Thanks for your time.
-
>>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 [100]; new returns the pointer. You can do anything you want with it. Also, a more streamlined version of int *Test(void) would be:
Code:
int *Test(void)
{
return (new int [100]);
}
You can directly return the value returned from new without needing any kind of local variable in between.
-
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
Code:
LocalPtr = FuncPtr;
The memory is still there, it's just referenced by a different name :-)
-
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 :-)