OSX lacks memalign

15,073

Solution 1

Mac OS X appears to be 16-byte mem aligned.

Quote from the website:

I had a hard time finding a definitive statement on MacOS X memory alignment so I did my own tests. On 10.4/intel, both stack and heap memory is 16 byte aligned. So people porting software can stop looking for memalign() and posix_memalign(). It’s not needed.

Solution 2

update: OSX now has posix_memalign()

Late to the party, but newer versions of OSX do have posix_memalign(). You might want this when aligning to page boundaries. For example:

#include <stdlib.h>

char *buffer;
int pagesize;

pagesize = sysconf(_SC_PAGE_SIZE);
if (pagesize == -1) handle_error("sysconf");

if (posix_memalign((void **)&buffer, pagesize, 4 * pagesize) != 0) {
  handle_error("posix_memalign");
}

One thing to note is that, unlike memalign(), posix_memalign() takes **buffer as an argument and returns an integer error code.

Solution 3

Why does the software you are porting need memalign() or posix_memalign()? Does it use it for alignments bigger than the 16-byte alignments referenced by austirg?

I see Mike F posted some code - it looks relatively neat, though I think the while loop may be sub-optimal (if the alignment required is 1KB, it could iterate quite a few times).

Doesn't:

amem += align - ((uintptr)amem & (align - 1));

get there in one operation?

Solution 4

From the macosx man pages:

The malloc(), calloc(), valloc(), realloc(), and reallocf() functions allocate memory. The allocated memory is aligned such that it can be used for any data type, including AltiVec- and SSE-related types. The free() function frees allocations that were created via the preceding allocation functions.

Solution 5

Yes Mac OS X does have 16 Byte memory alignment in the ABI. You should not need to use memalign(). If you memory requirements are a factor of 16 then I would not implement it and maybe just add an assert.

Share:
15,073
user17925
Author by

user17925

Updated on June 09, 2022

Comments

  • user17925
    user17925 about 2 years

    I'm working on a project in C and it requires memalign(). Really, posix_memalign() would do as well, but darwin/OSX lacks both of them.

    What is a good solution to shoehorn-in memalign? I don't understand the licensing for posix-C code if I were to rip off memalign.c and put it in my project- I don't want any viral-type licensing LGPL-ing my whole project.