Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - malloc and automatic storage

I understand that variables declared within a function have automatic storage. Does this mean it's not necessary to free pointers (p below) that have been explicitly allocated within a function call using malloc?

void f() {
  int *p;

  p = malloc(sizeof(int));
  *p = 1;
  printf("%p %d\n", p, *p);  // 0x7fc135c02850 1
  free(p);                   // is this necessary?
}

int main() {
  f();
}

(Note that I used a pointer to an int here, but the question applies to any pointer that's a return value of malloc and friends.)

I'm guessing no, since malloc allocates memory on the heap and not the stack; thus the memory p points to won't automatically be deallocated when the stack frame for f() is popped.

like image 861
yangmillstheory Avatar asked Jan 30 '23 05:01

yangmillstheory


2 Answers

p itself is automatic storage, and it will disappear when the function ends. What it points to however does need to be free()'d, at some point. For example, you could return the malloc()'d memory from the function, and free() it later on - p has still disappeared

like image 161
Steve Avatar answered Feb 08 '23 15:02

Steve


The memory you allocate with malloc() needs to be free()'d. In your case, automatic storage applies to the variable p itself, but not to the memory you allocated! When you use free(p), you free the memory p points to and not the p variable itself.

like image 21
Ronan Boiteau Avatar answered Feb 08 '23 16:02

Ronan Boiteau