0

I have declared an array/variable inside the function. I have been told that memory got allocated/declared in the function body is deallocated automatically when the function call ends. but when I imported the address of the memory allocated in function and dereferenced it in the main, the memory (i mean the value) still stays there. em a bit confused there.

#include <iostream>
using namespace std;
void fn(int *& ptr)
{
    int a = 10;
    ptr = &a;
}
void fn1(int*& ptr)
{
    int a[4] = { 3,4,5,6 };
    ptr = a;
}
int main()
{
    int* a = new int[5];
    for (int i = 00; i < 5; ++i)
        a[i] = i + 1;
    cout << *a << endl;
    a = 0;
    fn(a);
    cout << *a;
    a = 0;
    fn1(a);
    cout << endl << *a;
}

2 Answers2

3

The storage used for those variables is made available for reuse as soon as the function returns. That does not mean something will reuse it right away, so the values stored there previously may still be there.

Your program is invoking undefined behavior, which means anything can happen. It's OK if it prints the "deallocated" values, or it could crash, or print some other values, or it could telephone your mother and tell her you have violated the rules of C++ and please stop doing that.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
2

I think you're confusing ASDVs (automatic storage duration variables) and heap allocation.

ASDVs are commonly referred to as 'stack variables', albeit that's not in the standard. In your example, i is an ASDV, usually allocated on stack; it's destructed & deallocated after it goes out of scope.

Heap allocation is the result of new int[5]. This can (in your case, will) outlive the function and should be deallocated using delete. That also runs the destructor.

Note that, a itself (the pointer) is still an ASDV; the memory it points to is the result of heap allocation. So, even though a goes out of scope, that memory is not deallocated.

lorro
  • 10,687
  • 23
  • 36