Whats the correct replacement for posix_memalign in Windows? Whats the correct replacement for posix_memalign in Windows? windows windows

Whats the correct replacement for posix_memalign in Windows?


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

#ifdef _WIN32static 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)


_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.}


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