Cache aligning data structures

I want to align data structures in my application to cache lines. Here is a simple scenario :

typedef struct container {
  int a;
  int b;
} cont __attribute__((aligned(64));

int main() {
  cont *a;
  a = malloc( sizeof(cont) * 10);
  printf("%p", a);
  return 0;

In this case I thought that the starting address of the array will be cache aligned i.e. start at 64 byte boundary. But the address that is printed is 0x9dd008 which is not aligned to 64 byte boundary. Am I missing something in this implementation?


You're allocating from the heap, and the address returned is determined by malloc(). Since the code is already compiled, the compiler can't enforce the requested address alignment.

If you try allocating cont on the stack you should see the correct alignment.

You should use posix_memalign() to allocate memory with a specific memory alignment. In C11 you also have the opportunity to use aligned_alloc() that will provide the same functionality as posix_memalign() in other platforms (beside POSIX) as well.

Need Your Help

c++ source code on linux server and windows client?

c++ linux windows

This may be a really dumb question, but I hope to be able to clearly express myself.

jQuery-File-Upload not work with iframeupload and multiple file selection

jquery file upload blueimp

I get some problem with the blueimp/jQuery-File-Upload plugin.