3

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
3

4 Answers 4

6

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."

1
  • 1
    That's why it's a good idea always to set your pointer to NULL immediately after you've freed it.
    – Mr Lister
    Commented Jun 12, 2012 at 19:13
4

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.

2

It doesn't know. It just supposes it is valid and acts appropriately.

If this assumption was wrong, destruction of important structures might have occured - and what happens then, is not known. Thus the undefined behaviour.

1

Since the pointer is invalid, free tries to read the "book-keeping information" as if the pointer was returned by malloc and valid, which usually leads to freeing some random address pointed by that invalid pointer, leading to corruption/crash etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.