Search code examples
cmemorydynamicmallocflags

Create a flag for my own malloc implementation


So as I said in the title, I'm currently working on my own implementation of a dynamic memory allocation system.

The problem is, because i want the implementation to be as minimal as possible, to have a certain "flag" in memory which would indicate that the memory after is taken (+ his size)

I imagine a thing like this in memory : ...... | flag | size | (start_of_array) | ......

I think of using a big value like SIZE_MAX because it would technically look like 64 ones aligned in the memory and i don't think it is really common in memory to find this BUT it's not improbable thus this technic is error prone...

Is there a safer way to do this and create a value that will never be created by the machine by any mean ?

Thanks in advance !


Solution

  • Is there a safer way to do this and create a value that will never be created by the machine by any mean ?

    No, there is no value that you can safely assume would not be placed in memory other than by your allocator. And for what it's worth, SIZE_MAX is a particularly bad choice. It has multiple plausible uses itself, and it also has the same representation as -1 in the corresponding signed integer type, which has several uses of its own.

    You should not need to use a special value to recognize your memory blocks. You would typically allocate memory out of one or a small number of large, contiguous regions. Allocation metadata can be kept separately, but it's not uncommon for allocators to put metadata in the same space, similar to what you describe. All you need in that case is the location of the first block. The metadata accompanying that block, especially its recorded size, tells you how to find the next block (and whether there is one), and that tells you how to find the next, etc..