How to manage memory alignments and generic pointer arithmetics in a portable way in C?

后端 未结 6 478
暖寄归人
暖寄归人 2021-01-13 11:22

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 l

6条回答
  •  心在旅途
    2021-01-13 11:42

    aligned memory differs from compiler to compiler unfortunately (this is one issue), on MSVC, you have aligned_malloc, you also have POSIX memalign for Linux, and then there is also _mm_alloc which works under ICC, MSVC and GCC, IIRC, which should be the most portable.

    The second issue is memory wastage from aligning it, it wouldn't be major, but on embedded systems, its something to take note of.

    if you are stack allocating things that require alignment (like SIMD types), you also want to look into __attribute__((__aligned__(x))) and __declspec(align(x)).

    in terms of portability of pointer arithmetic, you can use the types from stdint.h/pstdint.h to do it, but the standards may say something about UB when casting between uintptr_t and a pointer (unfortunately standards aren't my strong point :().

提交回复
热议问题