I have to implement an optimized version of malloc/realloc/free (tailored for my particular application). At the moment the code runs on a particular platform, but I would like to write it in a portable way, if possible (the platform may change in the future), or at least I would like to concentrate the possible platform differences in a single point (probably a .h). I am aware of some of the problems:
(I'll ignore the differences in the basic system services for memory allocation here, since on some embedded systems they may be unavailable at all. Let's imagine that we work on a big preallocated memory block to be used as "heap").
The question(s):
Since malloc (or another dynamic memory allocator) is not necessarily guaranteed to align memory as we require, we'll need to perform two extra steps: Request extra bytes so we can returned an aligned address. Request extra bytes and store the offset between our original pointer and our aligned pointer.
Aligned Pointer means that pointer with adjacent memory location that can be accessed by a adding a constant and its multiples. for char a[5] = "12345"; here a is constant pointer if you and the size of char to it every time you can access the next chracter that is, a +sizeofchar will access 2.
The GNU documentation states that malloc is aligned to 16 byte multiples on 64 bit systems.
The type is important. While pointers are all the same size, as they just store a memory address, we have to know what kind of thing they are pointing TO.
The classic way to ensure that you maintain alignment suitable for all the basic types is to define a union:
union alloc_align {
void *dummy1;
long long dummy2;
long double dummy3;
};
...then ensure that the addresses you hand out are always offset by a multiple of sizeof (union alloc_align)
from the aligned addresses you recieve from the system memory allocator.
I believe a method similar to this is described in K&R.
Alignment features are only handled in the new C standard, C11. It has keywords _Alignof
, _Alignas
and a function aligned_alloc
. Theses features are not very difficult to emulate with most modern compilers (as indicated in other answers), so I'd suggest you write yourself small macros or wrappers that you'd use depending on __STDC_VERSION__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With