+ 1
confusion regarding returning array from function
#include<iostream> #include<conio.h> using namespace std; int* func() { int array[]={1,2,3,4,5,6,7,8,9}; return array; } int main() { int *ptr; ptr=func(); for(int i=0;i<10;i++) { cout<<ptr[i]<<" "; } return 0; } in the above program array base address is returned.. when program is executed using for loop the values given are some garbage value.. but when manually accessed each value in the main function like : ptr[0],ptr[2],ptr[3]...ptr[9] the values displayed are valid
2 Antworten
+ 3
This is undefined behaviour.
ptr is pointing somewhere that doesn't exist anymore.
Inside func() array is allocated on the stack which you then return, when the function is finished array is destroyed but ptr is still pointing there.
In order for array to not be destroyed you want to allocate on the heap (using new) instead so that it is not destroyed when the function ends, but you have to remember to call the proper delete when you're done with it or by using unique_ptr.
+ 1
func() returns a pointer to the array in it's stack frame, which had been freed. So the data is there, accessible by the old addresses, until something is pushed on the stack, that will overwrite the data. When you access the data "manually" you don't introduce new data on the stack and don't call any functions, so stack frame stays untouched. But when you're trying to print the data in the loop, you're calling a bunch of operator<<'s, effectively overwriting the old data on the stack. That's much like the fact that you can "restore" deleted data on disk, unless it has been overwritten.
Here's an example with comments:
https://code.sololearn.com/clSQFXQN6EV0/#cpp
P.S. Don't access objects that have been deleted.