int* a() {
int a_ = 5;
return &a_;
}
int main() {
int* p = a();
return 0;
}
Is a_
(aka p
here) allocated on the stack?
int* a() {
int a_ = 5;
return &a_;
}
int main() {
int* p = a();
return 0;
}
Is a_
(aka p
here) allocated on the stack?
Where is the memory allocated
int a_ = 5;
Automatic storage is allocated for a_
,
int* p = a();
Automatic storage is allocated also for p
Note that after a
has returned, the duration of the storage that was allocated for a_
has ended and therefore the pointer returned by a
is invalid.
That's from C++ and abstract machine perspective. From compiler / language implementation perspective, no memory needs to be allocated at all in this case since no observable behaviour depends on memory being allocated for the variables.
Is
a_
(akap
here) allocated on the stack?
a_
is allocated on the stack. The variable p
is allocated on the stack, too. The pointer value of p
is not required to point anywhere in particular, because dereferencing it would cause UB (see Can a local variable's memory be accessed outside its scope? for example).
At least one implementation (gcc 10.2, default options) compiles a()
to return nullptr
, which renders the question moot of where (the target of) p
was allocated.
Code:
#include <stdio.h>
int* a() {
int a_ = 5;
printf("&a_ = %p\n", &a_);
return &a_;
}
int main() {
int* p = a();
printf(" p = %p\n", p);
return 0;
}
&a_ = 0x7ffe7905ed9c
p = (nil)
[ EDIT ] To be pedantic, "allocated on the stack" should be read as "allocated on what's commonly referred to as stack, if one exists at all, and if the variable was actually allocated in memory as opposed to, for example, stored in registers or optimized away".