Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will C automatically free memory with no pointers?

Let's say we run this piece of code in isolation:

malloc(1024);

Will this result in a memory leak, or will C automatically know to free a pointer with no references?

In other words, can I avoid having to assign it to a pointer?

void *p = malloc(1024);
free(p);
like image 256
oink Avatar asked Mar 12 '26 19:03

oink


1 Answers

In any code you write which dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed. Freeing the memory is up to you.

If you assign a new block of memory to a pointer that currently points to an existing block of memory without first freeing the block, you have just overwritten the starting address for the original block of memory held by the pointer (violating rule 1 above) and you have now lost the ability to free the original block -- which is your memory leak.

like image 176
David C. Rankin Avatar answered Mar 15 '26 10:03

David C. Rankin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!