Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does free() 'know' that passed pointer is valid?

Tags:

c

pointers

free

I know that an invalid pointer leads to undefined behaviour but how does free know whether a pointer is valid or not?

Is there kind of a checksum at the beginning of each block in free list? something like:

if((*ptr) == 'CHECKSUM'))
  free
else
  do something undefined
like image 525
Matthias Avatar asked Aug 04 '26 21:08

Matthias


2 Answers

I know that an invalid pointer leads to undefined behaviour but how does free know whether a pointer is valid or not?

The only check is whether the pointer is null or not. If it's a null pointer, free (by specification) will do nothing.

Otherwise, free just tries to "free" the memory, making the assumption that it was memory allocated by malloc, calloc, or realloc, which can make anything happen (typically bad things) - hence "undefined behavior."

like image 173
Reed Copsey Avatar answered Aug 07 '26 13:08

Reed Copsey


There might be. But in general, it doesn't. For many implementations, free just assumes its input is valid and plows right ahead as though that's true. It is perfectly within its rights to do that.

This is why the behaviour is "undefined": it's impossible to predict what'll happen if the pointer isn't valid. Random areas of memory might get trashed, during the operation of free and/or later when some other heap operation is performed; potentially leading to unpredictable behaviour in unrelated code. The program may crash immediately in free, or later in some apparently unrelated locations.

like image 34
moonshadow Avatar answered Aug 07 '26 12:08

moonshadow



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!