Search code examples
c++memoryallocation

Where is the memory allocated if I declare a=5 then return &a?


int* a() {
  int a_ = 5;
  return &a_;
}

int main() {
  int* p = a();
  return 0;
}

Is a_ (aka p here) allocated on the stack?


Solution

  • 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.