Search code examples
chashfree

Why does free() put random chunks of data instead of deleting a node?


So, I'm studying hash tables and i'm on implementing one with an array and the collision resolving method being the chaining one. It seems to work well, but the deletion puts some random chunks of data in the place of the deleted item. I'm using free(node) in order to delete a node.


Solution

  • I guess you probably wrote something like this:

    free(bucket->node);
    

    That statement frees the memory pointed to by bucket->node, which mean the memory can be returned later by a call to malloc, or it can be returned to the operating system.

    Usually, unless the freed memory was quite large (like, megabytes), the memory is not returned to the operating system, for efficiency reasons. So the memory is probably still accessible to your program through the bucket->node pointer, but after free returns, the content of the memory is undefined (and has probably been changed to store housekeeping information used by the allocator).

    If you deference bucket->node after you called free(bucket->node), you commit a “use-after-free” error. The effects of this error are undefined but can be very serious. It is your responsibility to not dereference bucket->node after passing it to free.

    The usual way to avoid use-after-free is to immediately set the pointer to null. Example:

    free(bucket->node);
    bucket->node = 0;