This may seem like a very basic question, but its been in my head so:
When we allocate a local variable, it goes into stack. Similarly dynamic allocation cause the variable to go on heap. Now, my question is, is this variable actually lie on stack or heap or we will just a reference in the stack and Heap.
Suppose I declare a variable
I'm not entirely sure what you're asking, but I'll try my best to answer.
The following declares a variable
i on the stack:
When I ask for an address using
&i I get the actual location on the stack.
When I allocate something dynamically using
malloc, there are actually TWO pieces of data being stored. The dynamic memory is allocated on the heap, and the pointer itself is allocated on the stack. So in this code:
int* j = malloc(sizeof(int));
This is allocating space on the heap for an integer. It's also allocating space on the stack for a pointer (
j). The variable
j's value is set to the address returned by