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?
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)
_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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With