When I implemented my own version of malloc() in college, I used two linked lists: A free list and an allocated-buffers list (interspersed with calls to sbrk when I ran out). But now I have real-world issue: Our software malloc's buffers and puts them on linked lists where they may get freed hours later by code in one function or another. But very little code has the free() in the same function as the malloc()
This occasionally leads to a malloc'ed buffer being freed twice. Under Solaris, this was apparently not a problem because the app has been running for a looooong time. But running the code under Linux (RH) this bug suddenly has woken up.
I do not know the internal behavior of malloc() but it is obviously implementation-dependent. I do not know if the the Linux/gcc implementation maintains a list of allocated buffers. (The free list is a MUST; the allocated list? Not so much, I think.) Which leads me to the point of my questions:
- Does this implementation of malloc use a list of allocated memory areas?
- Is there a function (unofficial is fine by me) that will scan that list for a given pointer?
After reading a response my hmjd to a question by ant2009 my scheme, if the above answers are yes, is to replace calls to free() by a macro whose expanded code:
- Checks if the pointer is null, in which case it skips the next few steps
- Calls this mysterious function to insure it is still malloc'd
- Frees is by the book using free()
- Nulls the pointer as signal that it has been freed already; don't bother freeing again.
Such a function sure isn't in thI may e man pages but I would welcome. (As I write this, I am about to download glibc-2.17.tar.xz; find my answer there as well.)
Thanks. (Even for just reading this far!)
-- Jacob