void test(int pnt)
{
int* p = &pnt; //can a pointer get deallocated?
return;
}
Can pointers get deleted in this case? I don't know if they do. But I do know that if you get a pointer from the free store, it won't get deallocated.
void test(int pnt)
{
int* p = &pnt; //can a pointer get deallocated?
return;
}
Can pointers get deleted in this case? I don't know if they do. But I do know that if you get a pointer from the free store, it won't get deallocated.
The pointer p
is a local variable in the test
function so it gets deallocated when the function returns.
The argument pnt
is also a local variable in the test
function so it gets deallocated when the function returns.
If you returned &pnt
from the function, it would be a dangling pointer after the function returned, because the variable pnt
would have been destroyed.
int* test(int pnt) {
return &pnt; // bad idea, but technically you haven't done anything wrong yet
}
void test2() {
int* p = test(5);
cout << *p; // accesses a deallocated variable. Bad stuff happens here
}
If you returned p
, and p
did not point to a local variable, that is fine, because the thing it points to does not get destroyed, and the pointer variable itself is not relevant, as it only holds the pointer temporarily:
int pnt = 7; // global variable - doesn't get deallocated
int* test() {
int* p = &pnt;
return p; // this is fine. p is deallocated but we don't need p any more anyway
}
void test2() {
int* p = test();
cout << *p; // still fine, it prints 7
}