Why do I get different results when I dereference a pointer after freeing it?

It is undefined behaviour, so it is an error to deference freed pointer as strange things may (and will) happen.

free() doesn’t change the value of the pointer so it keeps pointing to the heap in the process address space – that’s why you don’t get segfault, however it is not specified and in theory on some platforms you can get segfault when you try to dereference pointer immediately after freeing.

To prevent this it is a good habit to assign pointer to NULL after freeing so it will fail in predictable way – segfault.

Please note that on some OSes (HP-UX, may be some others as well) it is allowed to dereference NULL pointer, just to prevent segfault (and thus hiding problems). I find it rather stupid as it makes things much more difficult to diagnose, although I don’t know the full story behind this.

Leave a Comment