tags:

views:

78

answers:

5

I created a class A and wrote the following function foo()

class A
{
public:
int a;
};

A * foo()
{
A a1;
return &a1;
}

int main()
{
A * a2;
a2 = foo();
return 0;
}

The compiler gave me a warning as a1 is a local variable and I am returning its address from the stack (so its value can change unpredictably).

Now I changed foo() to the following

A * foo()
{
A a1;
A *a3;
a3 = &a1;
return a3;
}

Now the compiler does not give any warning. Is this because a3 is created on the heap? If so are pointers always created on heap like this. I thought heap is utilized only through new/malloc.

+1  A: 

Your code is still invalid. Your compiler just gives very bad warnings.

Clark Gaebel
Technically the code is valid, as long as nothing ever uses the return value of foo().
David Thornley
+1  A: 

No, it is only because the compiler is not smart enough to understand that a3 points to a1, which is on the stack.

What you are doing is still undefined. It would be better to pass in a variable and set it like this:

void foo(A& a1)
{
    a1.something = 1;
    a1.somethingElse = 2;
}

or use smart-pointers.

BlueRaja - Danny Pflughoeft
Is a3 on the stack?
Bruce
@Bruce: Yes a3 is on the stack, but its VALUE is a memory address. That memory address can be returned by value, just like an int, which is why `return a3;` would be valid if a3 pointed to something non-temporary. As it stands, however, that memory address is an address in the stack, which is released when the function returns; that's why that memory address isn't a valid return-value (returning it is undefined behavior)
BlueRaja - Danny Pflughoeft
_Returning_ a pointer from a function that points to a local variable does not result in undefined behavior. _Using_ such a pointer does. There is a subtle but important difference between the two.
James McNellis
@James: I would say the difference is not so much important as it is pedantic. There is no reason to ever do this.
BlueRaja - Danny Pflughoeft
@BlueRaja: I agree.
James McNellis
+4  A: 

Now the compiler does not give any warning.

The compiler isn't giving any warning because you've added sufficient complexity to fool the analysis that it does of your code.

You are still returning a pointer to a local variable, and you cannot use that pointer after the function has returned.

James McNellis
Is a3 on the stack or the heap?
Bruce
@Bruce: `a1` and `a3` are both on the stack. A copy of the pointer `a3` is made when you return it from the function, but this has no effect on the object pointed to by `a3`.
James McNellis
+1  A: 

The compiler is only looking at warnings one level of indirection deep - the second example is just as dangerous as the first.

Martin Beckett
+1  A: 

You're still returning the address of an item allocated on the stack (so it's still wrong). But because you added another layer of indirection, you've prevented the compiler from detecting that and warning you.

Mark B