I'm new to malloc and aligned malloc. I know how to use them. However, I don't know exactly in which case we should use aligned malloc instead of standard malloc. Can you explain it to me please?
-
Language? I assume C, but you should also provide other environment details (OS, language implementation, etc). Standard C has only `malloc`, guaranteed to be correctly aligned for all standard data types. – paxdiablo Sep 24 '16 at 13:55
-
I use in C11 standard in Ubuntu – blackcafe Sep 24 '16 at 14:03
-
Added those as tags, please confirm and/or change as necessary. – paxdiablo Sep 24 '16 at 14:06
-
I have put them as tags, sorry – blackcafe Sep 24 '16 at 14:08
1 Answers
The glibc
documentation makes it reasonably clear where you should use aligned_alloc
:
The address of a block returned by
malloc
orrealloc
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, usealigned_alloc
orposix_memalign
.
The C standard already guarantees that malloc
will return a suitably aligned memory block for any of the standard types but there may be situations in which you want or need stricter alignment.
As one example, I seem to recall that SSE2 (SIMD) instructions need their data aligned on 16-byte boundaries so you could use aligned_alloc
to give you that even on systems where malloc
only guarantees alignment to an 8-byte boundary.

- 854,327
- 234
- 1,573
- 1,953