C - malloc and automatic storage

I understand that variables declared inside a function have automatic storage . Does this mean that there is no need for pointers free( pbelow) that are explicitly highlighted in the function call with 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 here int, but the question applies to any pointer returning a value mallocand friends.)

I guess not, because it mallocallocates memory on the heap, not the stack; thus, the memory point pindicates that it will not be freed automatically when the stack frame for is inserted f().

+4
source share
4

p , , ​​ . , , , free()'d, - . , malloc()'d , free() - p -

+3

, malloc(), free() 'd. p, ! free(p), p , p.

+3

That's right, a challenge is needed free.

+1
source

If you request manual allocation of memory, you must manually free up the space you requested. So there is free

+1
source

Source: https://habr.com/ru/post/1689345/


All Articles