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.