Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Pointers and scope

Tags:

c++

pointers

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?

like image 457
oh boy Avatar asked Apr 30 '10 16:04

oh boy


1 Answers

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.

like image 135
Mark Rushakoff Avatar answered Sep 30 '22 00:09

Mark Rushakoff