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:
- differences in memory alignment
- differences in smallest memory blocks size suitable for “generic” allocation
- differences in pointer size
(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):
- Are there standard macros or functions in C for this kind of purpose?
- What other issues may I face in this job?
Alignment features are only handled in the new C standard, C11. It has keywords
_Alignof,_Alignasand a functionaligned_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__.