Home > Mobile >  is it OK if some malloc() implementation returns aligned addr by default?
is it OK if some malloc() implementation returns aligned addr by default?

Time:10-09

I want to implement my own malloc() and aligned_alloc() for debugging purposes. The question is, what problems can I face if malloc() will work the same as aligned_alloc() for sizeof(void*) alignment by default?

CodePudding user response:

As far as I know, malloc implementations already return aligned pointers anyway. The one I know about have to: since the ((size_t *)ptr)[-1] contains a size, it has to be aligned to be able to store a size_t. That is just an implementation thing. So, afaik, there is no theory saying "it has to be aligned". But, well, there must be a way to store the allocated size, or, something that can leed to it, so that free knows what to deallocate.

So, there is no problem at all in the fact that malloc returns aligned pointers. As long as you are coherent with it. Of course, it is a waste of some bytes if people use malloc(1) in cascade. But, well, it would have been any way, because the "heap metadata" (the ptr[-1] thing) would not be negligible as they should be.

The difference with aligned_alloc is that you can specify the alignment, to have a stricter one than the one it provides anyway.

  • Related