5 ms·
Perhaps malloc() could allocate 1 byte extra at the start of the allocated block with some magic number written to it and free() could assert that the number is
by mixedbit 7y ago
Perhaps malloc() could allocate 1 byte extra at the start of the allocated block with some magic number written to it and free() could assert that the number is correct and change the number to mark the block as freed.
- deleted 7y ago[deleted]
- vardump 7y agoProblems: double free might still happen, except now some innocent memory block can be corrupted as well, which just happened to have the magic value in that address. All memory allocations are now misaligned, decreasing performance. On some platforms misaligned access causes a bus error exception. The marker would generally need to be at least 8 bytes. This would alleviate the problems, but also cause pretty significant overhead.
- saagarjha 7y agoI feel like the allocation header might already have a flags bit field where this might go.
- laughinghan 7y agoOn the other hand, the chances of an innocent memory block having a random 8-byte magic value is vanishingly small, so that would work even better. If free() took only 1ns to run and you called it 2^64 times, that would take >500 years.
- bluecalm 7y agoWhy not just always set the pointer to NULL after free is called in it? It would be fantastic if the operation is atomic as well but even if it isn't I like doing it. Freed address is not something you ever want to just again anyway.
- mixedbit 7y agoThere can be many pointers pointing to the same allocated memory. For example, if you have a cyclic list with two elements head.next and head.prev pointers will both point to the second element and free(head.next); free(head.prev); would be double-free.
- bluecalm 7y agoWhen many pointers point to the same memory then naked free shouldn't be used. Instead you implement a counter and decrease it (and free at zero when the last pointer dies). Imo code where a free is called on something other pointers point to is just a basic level design error.
- jandrese 7y agoBecause in this case the problem is a second pointer to the same chunk of data. Nulling the first doesn't null the second.
- seppel 7y agoThe metadata (size of allocated block, and whether it is in use) is already there. I really wonder why this is not checked. In a normal libc you should get a "double free" panic.
- kccqzy 7y agomalloc() doesn't give you memory on the granularity of bytes. On x86_64 for example malloc has to assume you'll use the memory for 16-byte aligned access (say, movdqa). So your allocating an extra byte could become 16 extra bytes.