Take the 2-minute tour ×

I want to make a multi-thread C program with a proper variable alignemt in cache, to avoid "cache sloshing". I get cache-line length from /sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size, so I know how to pad my arrays to occupy full cache lines.

But, how can I be sure that an array is allocated exactly at the beginning of a cache line? Or is it automatic? (If it was automatic, I would not care about the padding...)

share|improve this question
The usual warning: are you sure this really matters ? Aren't you doing premature optimization ? –  Alexandre C. Jul 29 '11 at 12:10
More about curiosity than optimization –  Jakub M. Jul 29 '11 at 12:32

2 Answers 2

up vote 3 down vote accepted

To allocate memory with a specific alignment, use posix_memalign.

(I don't know whether the memory allocator is intelligent enough to allocate on cache-line boundaries automatically, though.)

share|improve this answer
+1, but one should perhaps say, well the name indicates it, that this is system dependent. The OP didn't say explicitly that he is on a POSIX system. –  Jens Gustedt Jul 29 '11 at 12:02
Also this only works for allocation on the heap. –  Jens Gustedt Jul 29 '11 at 12:07

I don't think that there is a portable standard C function that ensures this directly. A portable way to do this is to allocate slightly more memory than you need and then offset the part that you really use to the first address that fulfills your alignment requirements. This would work for heap and stack memory, equally.

The disadvantage of this is that for malloced memory, you'd always have to keep a pointer to the original memory somewhere such that you can use free on that, afterwards.

share|improve this answer
So, some "tricks" with pointer's values like p2=p+line_length-p%line_length would be equivalent to proper alignment? –  Jakub M. Jul 29 '11 at 12:37
On an architecture with non-segmented memory, something in that direction would do it I think. But you'd certainly have to cast to and from char* to obtain the desired result. On segmented memory you'd perhaps have to be more careful if there is a segment boundary towards the start of the buffer... –  Jens Gustedt Jul 29 '11 at 12:47

Your Answer


