3

Possible Duplicate:
Aligned memory management?

I have an array which I am declaring like this

int * myarray;
int num_of_element;

myarry = (int*) calloc(num_of_elements, sizeof(int));

The size of an int is 4 bytes however I want to ensure that my array starts on an 8 byte boundary - so I can efficiently load two values each time. Is there a different way or something else I can do?

Community
  • 1
  • 1
Markus
  • 589
  • 1
  • 6
  • 19

2 Answers2

2

There are several ways.

  1. Over-allocate, and round up the returned address to the desired alignment.

  2. Define a union with a type whose alignment is the desired one, generally double. This requires low-level knowledge but is not optimal when you want to allocate an array.

Also, you shouldn't cast the return value of malloc() in C.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
2

Did you tried posix_memalign ?

The function posix_memalign() allocates size bytes and places the address of the allocated memory in *memptr. The address of the allocated memory will be a multiple of alignment, which must be a power of two and a multiple of sizeof(void *).

Example:

if (posix_memalign(&myarray, 8, num_of_elements*sizeof(int)) != 0) {
    // failed
}

See http://pubs.opengroup.org/onlinepubs/009696699/functions/posix_memalign.html

Linux posix_memalign manpage also documents aligned_alloc() (c11), memalign() (obsolete) :

https://www.kernel.org/doc/man-pages/online/pages/man3/posix_memalign.3.html

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194