2

I guess this is a very basic question, but even after looking around on the internet for a while I can't seem to find a proper answer to this question. I will refer to this tutorial on stack/heap:http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html

Let's say I write the following code:

void testVoid() {
   int testVariable = 5;
}

If I'm not wrong, this function should create a variable located on the stack. As the functions exits, the allocated memory on the stack is deleted - so my variable should also have been deleted by then.

I have learned that pointers in c++ point to the memory location of a variable. So if the variable pointed to by a pointer is located on the stack, and the stack then is cleared, I would expect not to be able to access original value through the pointer anymore, since the memory location pointed to is is cleared. However, I tested this:

int* pointer;

void testVoid() {
    int num = 3;
    pointer = # // Here I get the memory location of my num-variable
    cout << pointer << " : " << *pointer << endl;  // I would get the same result if i printed &num
}

int main(int args, char** argv) {

    pointer = new int;
    testVoid();
    cout << pointer << " : " << *pointer << endl;  // I can still access the memory of my num-variable

    while (true) {}

    return 0;
}

After exiting the testVoid()-function, where the variable is created, I can still get the value of the variable using my pointer. So obviously I have misunderstood something regarding how pointers work in c++. Printing &pointer and &num gives me the same memory location, even after testVoid() has finished. What is the reason for this? If the memory pointed to by the pointer were moved to the heap, shouldn't cout<<&num and cout<

And here's the output: 0024F904 : 3 0024F904 : 3

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Value has not be cleared (why it should?) but it doesn't mean you can ACCESS it. As you know it's UB so...by definition it's undefined (it may _even work_ until that memory location is overwritten by something else but you just can't rely on that). – Adriano Repetti Sep 25 '14 at 11:50
  • So when a function exits, the memory of its' variables is not cleared, but it can be overwritten later, right? That makes a lot more sense! Thank you very much! – MyNiceDisplayName Sep 25 '14 at 12:04
  • Yes, it's like that but you can't really do any assumption. Memory may be cleared, deallocated, marked to throw an exception if you access it, untouched or reused for next call to your function. It's completely system and implementation defined (UB means anything is good). – Adriano Repetti Sep 25 '14 at 12:07
  • Ok, this answers my question. Thank you very much. – MyNiceDisplayName Sep 25 '14 at 12:19

1 Answers1

1

Just because the value goes out of scope does not mean the memory for the value has been overwritten. You just can't rely on it being stable at that point.

Brandon Kohn
  • 1,612
  • 8
  • 18