Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allocate and free aligned memory in C

Tags:

How do you allocate memory that's aligned to a specific boundary in C (e.g., cache line boundary)? I'm looking for malloc/free like implementation that ideally would be as portable as possible --- at least between 32 and 64 bit architectures.

Edit to add: In other words, I'm looking for something that would behave like (the now obsolete?) memalign function, which can be freed using free.

like image 671
fuad Avatar asked Dec 17 '09 02:12

fuad


People also ask

Does malloc allocate aligned memory?

3.6 Allocating Aligned Memory Blocks. The address of a block returned by malloc or realloc in GNU systems is always a multiple of eight (or sixteen on 64-bit systems). If you need a block whose address is a multiple of a higher power of two than that, use aligned_alloc or posix_memalign .

Is malloc 16 byte aligned?

The GNU documentation states that malloc is aligned to 16 byte multiples on 64 bit systems.

Why is malloc aligned?

malloc has no knowledge of what it is allocating for because its parameter is just total size. It just aligns to an alignment that is safe for any object.

How malloc is implemented in C?

When one calls malloc , memory is taken from the large heap cell, which is returned by malloc . The rest is formed into a new heap cell that consists of all the rest of the memory. When one frees memory, the heap cell is added to the end of the heap's free list.


2 Answers

Here is a solution, which encapsulates the call to malloc, allocates a bigger buffer for alignment purpose, and stores the original allocated address just before the aligned buffer for a later call to free.

// cache line #define ALIGN 64  void *aligned_malloc(int size) {     void *mem = malloc(size+ALIGN+sizeof(void*));     void **ptr = (void**)((uintptr_t)(mem+ALIGN+sizeof(void*)) & ~(ALIGN-1));     ptr[-1] = mem;     return ptr; }  void aligned_free(void *ptr) {     free(((void**)ptr)[-1]); } 
like image 163
Jerome Avatar answered Sep 20 '22 20:09

Jerome


Use posix_memalign/free.

int posix_memalign(void **memptr, size_t alignment, size_t size);   void* ptr; int rc = posix_memalign(&ptr, alignment, size); ... free(ptr) 

posix_memalign is a standard replacement for memalign which, as you mention is obsolete.

like image 45
Lucian Adrian Grijincu Avatar answered Sep 17 '22 20:09

Lucian Adrian Grijincu