Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question on free() in C language [duplicate]

Tags:

c

memory

Possible Duplicate:
How do free and malloc work in C?

How does free know how many bytes of memory to be free'd when called in a program?

like image 889
Pradeep Nayak Avatar asked Dec 09 '22 10:12

Pradeep Nayak


1 Answers

This is implementation specific, but when malloc is called, the size of the allocated memory is kept somewhere (usually offset from the pointer itself). When free is called, it will use that stored size.

This is exactly why you should only ever call free on a pointer that was returned by malloc.

like image 155
Kevin Avatar answered Dec 11 '22 22:12

Kevin