I am confused about the memory allocation in C++. Can anyone guide me as to where each of the variable in the below snippet is getting allocated. How can I determine what is getting allocated on stack and what gets allocated on heap. Is there any good web reference for learning this.
class Sample {
private:
int *p;
public:
Sample() {
p = new int;
}
};
int* function(void) {
int *p;
p = new int;
*p = 1;
Sample s;
return p;
}
If it’s created via
new, it’s in the heap. If it’s inside of a function, and it’s notstatic, then it’s on the stack. Otherwise, it’s in global (non-stack) memory.