Search code examples
c++macosmallocposix

How to wrap posix_memalign (to compile an old codebase on mac)?


I am trying to compile a toolkit on mac. It has a reference to memalign function of malloc.h, but the only close function I could find for mac is posix_memalign. So I am trying to wrap posix_memalign to look like memalign.

I am a bit confused about how to do this (because of the void* and void** pointers):

The signature for posix_memalign is

int posix_memalign(void **memptr, size_t alignment, size_t size); 

and the signature for memalign is:

void *memalign(size_t blocksize, size_t bytes);

Any pointers much appreciated. ( Lame pun accidental! :)

thanks


Solution

  • Something like:

    void *memalign(size_t blocksize, size_t bytes) {
      void *result=0;
      posix_memalign(&result, blocksize, bytes);
      return result;
    }
    

    The &result will get you a void** to call posix_memalign with and then you can return the result as memalign did.

    One point to note: this doesn't quite match the behaviour - memalign returns errors via errno, but posix_memalign returns them as an int and doesn't touch errno. You should see to it that errors are handled appropriately somehow still.