Search code examples
cmallocmagic-numbersheapalloc

Searching for a safe magic number for in-memory data structure



I'm implementing a heap allocator (malloc), and I need to choose a magic number to check if a given pointer point to a data structure I allocated. It seems obvious to me that no magic number can be considered completely safe (if the number is checked, I can be sure a point to one of my data structure), but maybe I missed something, so... if someone can help and bring me the number of my dreams, I'd really appreciate. Thx in advance.


Solution

  • It depends on what you're doing this for. If you're doing it to try and catch programming mistakes (e.g., you want to make sure you don't accidentally mix up my_malloc/my_free and malloc/free), then just pick a random value. Sure, sometimes it'll fail to detect such a case, but that really doesn't matter. It shouldn't ever happen. So, here:

    #define MAGIC_32BIT 0x77A5844CU
    #define MAGIC_64BIT 0xD221A6BE96E04673UL
    

    If correctness depends on this, then you really ought to do this another way. For example, by keeping track of which addresses you've allocated in a hash or tree or, in special cases, a bitmap.

    If you're actually implementing malloc/free (e.g., writing your own C library), then keep in mind that freeing something that wasn't malloced (except NULL) is undefined behavior by the standard, so your code doesn't need to worry what happens.