Arash Arash - 11 days ago 4
C Question

What happens to malloc variable in a function?

Assume I create a variable inside a function by using


int f()
int* i=(int*)malloc(sizeof(int));
/* ... */

Where is variable
located? In heap or in function


I'm going to use p instead of i, because variables named i are most often integers.

void function(void) {
    int *p = malloc(sizeof(*p));

There are two things here: p and *p with the following relationship:

  stack          heap
│   ... │     │   ... │
┢━━━━━━━┪     ┢━━━━━━━┪
┃     p ┃ ──→ ┃    *p ┃
┡━━━━━━━┩     ┡━━━━━━━┩
│   ... │     │   ... │

Once you return from the function, p is gone. However, *p will remain allocated until you call free(). Forgetting to call free() means you have a "memory leak", because *p will stick around forever even though you can't use it (because p is gone).

Note: p is not necessarily on the stack, but you can pretend that it is. It could be in a register or optimized out entirely. It can even move around on the stack. The whole concepts of "stack" and "heap" are technically implementation-specific anyway.