Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this C++ code work? Stack memory and pointers

Here is some C++ code.

#include <iostream>
using namespace std;

class test{
    int a;
  public:
    test(int b){
    a = b;
    cout << "test constructed with data " << b << endl;
  }
  void print(){
    cout << "printing test: " << a << endl;
  }
};

test * foo(){
    test x(5);
    return &x;
}

int main()
{
    test* y = foo();
    y->print();
    return 0;
}

Here is its output:

test constructed with data 5
printing test: 5

My question: Why does the pointer to x still "work" outside of the context of function foo? As far as I understand, the function foo creates an instance of test and returns the address of that object.

After the function exits, the variable x is out of scope. I know that C++ isn't garbage collected- what happens to a variable when it goes out of scope? Why does the address returned in foo() still point to what seems like a valid object?

If I create an object in some scope, and want to use it in another, should I allocate it in the heap and return the pointer? If so, when/where would I delete it

Thanks

like image 577
user2445455 Avatar asked Dec 25 '13 21:12

user2445455


1 Answers

x is a local variable. After foo returns there's no guarantee that the memory on the stack that x resided in is either corrupt or intact. That's the nature of undefined behavior. Run a function before reading x and you'll see the danger of referencing a "dead" variable:

void nonsense(void)
{
    int arr[1000] = {0};
}

int main()
{
    test* y = foo();
    nonsense();
    y->print();
    return 0;
}

Output on my machine:

test constructed with data 5
printing test: 0

like image 141
Fiddling Bits Avatar answered Sep 28 '22 15:09

Fiddling Bits