c - memory allocation in Stack and Heap -
this may seem basic question, been in head so:
when allocate local variable, goes stack. dynamic allocation cause variable go on heap. now, question is, variable lie on stack or heap or reference in stack , heap.
for example,
suppose declare variable int i
. i
allocated on stack. so, when print address of i
, 1 of location on stack? same question heap well.
i'm not entirely sure you're asking, i'll try best answer.
the following declares variable i
on stack:
int i;
when ask address using &i
actual location on stack.
when allocate dynamically using malloc
, there two pieces of data being stored. dynamic memory allocated on heap, , pointer allocated on stack. in code:
int* j = malloc(sizeof(int));
this allocating space on heap integer. it's allocating space on stack pointer (j
). variable j
's value set address returned malloc
.
Comments
Post a Comment