I've read the followed post:
Is returning a heap-allocated pointer from function OK?
Which shows that a pointer pointing to a heap allocated variable is returned is alright. However, is the pointer technically a "stack allocated variable", which would then get deallocated upon returning of the function?
For example:
int* test(){
int arr[5];
int *ptr = arr;
return ptr; //deallocated ptr?
}
int *test2(){
int arr[5];
return arr;
}
In test
Also, is it right to say arr is a pointer that points to some newly created int array arr, pointing at &arr[0]
. If arr
is not a pointer, why is it valid to return it satisfying the function return type?
Since both ptr and arr are supposedly stack allocated, why does the code only work in test()
and not test2()
? Does test() give an undefined behavior?