C - malloc and automatic storage

Viewed 383

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.

4 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

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.

Correct, a call to free is necessary.

If you ask for memory allocate manually, you must free manually the space you asked for. So free is necessary there

Related