Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the correct replacement for posix_memalign in Windows?

I currently trying to build word2vec in Windows. But there are problems with posix_memalign() function. Everyone is suggesting to use _aligned_malloc(), but the number of parameters are different. So what's the best equivalent for posix_memalign() in Windows?

like image 206
ZFTurbo Avatar asked Nov 13 '15 15:11

ZFTurbo


3 Answers

Thanks everyone. Based on code I fond in some repository and your advices I build EXE sucessfully. Here the code I used:

#ifdef _WIN32
static int check_align(size_t align)
{
    for (size_t i = sizeof(void *); i != 0; i *= 2)
    if (align == i)
        return 0;
    return EINVAL;
}

int posix_memalign(void **ptr, size_t align, size_t size)
{
    if (check_align(align))
        return EINVAL;

    int saved_errno = errno;
    void *p = _aligned_malloc(size, align);
    if (p == NULL)
    {
        errno = saved_errno;
        return ENOMEM;
    }

    *ptr = p;
    return 0;
}
#endif

UPDATE:

Looks like @alk suggest the best sollution for this problem:

#define posix_memalign(p, a, s) (((*(p)) = _aligned_malloc((s), (a))), *(p) ?0 :errno)

like image 178
ZFTurbo Avatar answered Nov 19 '22 20:11

ZFTurbo


_aligned_malloc() should be decent replacement for posix_memalign() the arguments differ because posix_memalign() returns an error rather than set errno on failure, other they are the same:

void* ptr = NULL;
int error = posix_memalign(&ptr, 16, 1024);
if (error != 0) {
  // OMG: it failed!, error is either EINVAL or ENOMEM, errno is indeterminate
}

Becomes:

void* ptr = _aligned_malloc(1024, 16);
if (!ptr) {
  // OMG: it failed! error is stored in errno.
}
like image 23
mauve Avatar answered Nov 19 '22 21:11

mauve


Be careful that memory obtained from _aligned_malloc() must be freed with _aligned_free(), while posix_memalign() just uses regular free(). So you'd want to add something like:

#ifdef _WIN32
#define posix_memalign_free _aligned_free
#else
#define posix_memalign_free free
#endif
like image 3
Fred B Avatar answered Nov 19 '22 21:11

Fred B