Memory allocation confusion
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.
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.
Your code is still invalid. Your compiler just gives very bad warnings.
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.
The compiler is only looking at warnings one level of indirection deep - the second example is just as dangerous as the first.
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.
精彩评论