About Heap Memory

Heap memory is a memory that is not bounded by the scope and remains even when the variable goes out of scope. So is it like global variable?

int* create(){                                             
   int *a = new int(5);                                   
   return a;                                              
}                                                          
                                                       
                                                       
int main(){                                                
   fastIO;                                                
   int *b = create();                                     
   cout << *b << endl;                                    
   cout << *a << endl;                                    
} 

Now in this program, both the cout must give output but its shows compilation error that *a is not declared

I think the code is incorrect. It should be this ( I guess).

#include <bits/stdc++.h>
using namespace std;
int *a;
int *create() {
    a = new int(5);
    return a;
}

int main() {
    int *b = create();
    cout << *b << endl;
    cout << *a << endl;
}

Yeah I know that the code is incorrect but I was saying that if a is defined in heap memory which is not destroyed when variable goes out of scope then is it not same as global variable? We can define it in any function and we can always use it anywhere in the program.

And if we have to return the value as we did for variables stored in stack memory then what’s difference between storing value in stack and heap memory

I am not sure about what you’re asking, hope this helps.

1 Like

It will be there but its scope is just limited to create function.
Hope I’ve answered your question.

1 Like

Yeah I got this

Every time when we made an object it always creates in Heap-space and the referencing information to these objects are always stored in Stack-memory.

This line makes it clear why we have to return the value to use it in main(), as not doing so will result in lost of reference to the memory.