C’s Revenge

Your C programming tip for today:

When freeing a block of memory, make absolutely sure that there’s nothing else that’s ever going to use it again first.

Especially when that block of memory is being used as part of the processor’s page tables. If you do, your program won’t segfault. It won’t even act strangely in the usual “undefined behavior in C” sense. Oh no. Now the processor’s going to be doing who knows what, since its very notions of what memory looks like have been mangled. There’s no telling what happens after that, but it certainly won’t be anything good.

3 Responses

  1. This is why it’s nice to make drop-in malloc/free/new/delete/etc. replacements which fill memory with known junk values as necessary, using ld tricks or whatever. You can also add in nifty things like pre/postguard bands so you can see if you’re ever overflowing a buffer or whatever. This was extremely useful during the development of Sprung.

  2. malloc? free? Those are way too high-level for a virtual memory subsystem in a toy OS. But ordinarily it’s good advice.

  3. s/(malloc|free)/your_equivalent_memory_management_function_name/g

Comments are closed.