What is aligned memory allocation?

后端 未结 4 1563
臣服心动
臣服心动 2020-12-01 09:29

I also want to know whether glibc malloc() does this.

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 10:01

    The malloc() documentation says:

    [...] the allocated memory that is suitably aligned for any kind of variable.
    

    Which is true for most everything you do in C/C++. However, as pointed out by others, many special cases exist and require a specific alignment. For example, Intel processors support a 256 bit type: __m256, which is most certainly not taken in account by malloc().

    Similarly, if you want to allocate a memory buffer for data that is to be paged (similar to addresses returned by mmap(), etc.) then you need a possibly very large alignment which would waste a lot of memory if malloc() was to return buffers always aligned to such boundaries.

    Under Linux or other Unix systems, I suggest you use the posix_memalign() function:

    int posix_memalign(void **memptr, size_t alignment, size_t size);
    

    This is the most current function that one wants to use for such needs.

提交回复
热议问题