aligned_alloc - Linux


aligned_alloc allocates a block of memory of a specified size that is aligned on a specified boundary. It is useful for situations where data structures require specific alignment for optimal performance.


void *aligned_alloc(size_t alignment, size_t size);




  • Align a memory block to 32 bytes:

    void *ptr = aligned_alloc(32, sizeof(int) * 10);
  • Allocate a 16-byte aligned buffer for a cache-optimized data structure:

    struct my_data_struct *data = aligned_alloc(16, sizeof(struct my_data_struct));

Common Issues

  • Invalid alignment: Passing an invalid alignment value (not a power of 2) or an alignment greater than the system page size may result in undefined behavior.
  • Failed allocation: If the system cannot allocate memory with the specified alignment, aligned_alloc returns NULL.


aligned_alloc can be used in conjunction with other memory management functions like free:

void *ptr = aligned_alloc(32, sizeof(int) * 10);

Related Commands

  • malloc, realloc: General-purpose memory allocation functions.
  • memalign: Allocates memory with alignment specified in bytes.
  • valloc: Allocates memory aligned to the page size.