int* test( )
{
int a = 5;
int* b = &a;
return b;
}
Will the result of test
be a bad pointer
? As far as I know a should be deleted and then b
would become a messed up pointer, right?
How about more complicated things, not an int pointer but the same with a class with 20 members or so?
The term for what you're returning is a "dangling pointer". a
is a local variable allocated on the stack, and it is no longer available once it goes out of scope (which is something completely different from garbage collection). Attempting to use the result of a call to test()
will be undefined behavior.
On the other hand, if you didn't allocate a
on the stack -- (int *a = new int(5);
), then int *b = a; return b;
would be just fine, although not as good as return new int(5)
. However, if you don't properly free
the result later, you will have a memory leak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With