You are not allowed to call free on unallocated memory, the standard states that quite clearly:
The free function causes the space pointed to by its argument to be deallocated, that is, made
available for further allocation. If the argument is a null pointer, no action occurs. Otherwise, if
the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined (slightly paraphrased, my emphasis).
What happens, for example, if the address you're double-freeing has been reallocated in the middle of a new block and the code that allocated it just happened to store something there that looked like a real malloc-block header? Like:
+- New pointer +- Old pointer
v v
+------------------------------------+
| <Dodgy bit> |
+------------------------------------+
Chaos, that's what.
Memory allocation functions are a tool just like a chainsaw and, provided you use them correctly, you should have no problems. If you misuse them, however, the consequences are your own fault, either corrupting memory or worse, or cutting off one of your arms :-)
And regarding the comment:
it can communicate gracefully to enduser about the doubling free the same location
Short of keeping a record of all malloc and free calls to ensure you don't double-free a block, I can't see this as being workable. It would require a huge overhead and still wouldn't fix all the problems.
What would happen if:
- thread A allocated and freed memory at address 42.
- thread B allocated memory a address 42 and started using it.
- thread A freed that memory a second time.
- thread C allocated memory a address 42 and started using it.
You then have threads B and C both thinking they own that memory (these don't have to be threads of execution, I'm using the term thread here as just a piece of code that runs - it could all be in the one thread of execution but called sequentially).
No, I think the current malloc and free are just fine provided you use them properly. By all means give some thought to implementing your own version, I see nothing wrong with that but I suspect you'll run into some pretty thorny performance issues.