Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the stack variable deallocated when it goes out of scope? [duplicate]

Tags:

c++

c++11

sample1.cpp

#include <iostream>

int main()
{
    int* aPtr = nullptr;

    {
        int a = 3;
        aPtr = &a;
    }

    std::cout << *aPtr << std::endl;

    return 0;
}

Output

3

I am able to access a through aPtr.

  1. Does that mean a is not deallocated even after it goes out of scope.
  2. Does that mean a is deallocated only after the function in which it is defined unwinds.
  3. Or is this an undefined behavior that currently outputs some value?

sampe2.cpp

#include <iostream>

struct Box
{
    Box(int a_)
        :a(a_)
    {}

    int getValue() const { return a;}

    ~Box()
    {
        std::cout << "Destructor called" << std::endl;
    }
private:
    int a;
};


int main()
{
    Box* boxPtr = nullptr;

    {
        Box box = 23;
        boxPtr = &box;
    }

    std::cout << boxPtr->getValue() << std::endl;

    return 0;
}

Output

Destructor called
23

I am able to access box through boxPtr even after destructor of box is called.

like image 239
Vivek Avatar asked Aug 31 '18 05:08

Vivek


1 Answers

As mentioned in the comments, in both cases you are facing undefined behavior (so anything is allowed to happen). The stack variables are destroyed as soon as they go out of scope, the memory occupied by them is freed, although usually it's not immediately overwritten (at least in simple cases like above), therefore the pointer pointing at such variable, might sometimes exhibit more or less "valid" properties (as in it looks like the object is still valid), despite it clearly dangling.

like image 198
paler123 Avatar answered Dec 06 '22 20:12

paler123