Is the memory alignment by mxCalloc and/or mxMalloc defined
3 views (last 30 days)
Show older comments
Chester Gillon
on 7 Jul 2014
Commented: Chester Gillon
on 8 Jul 2014
I want to create a MEX function for MATLAB 2014a which uses AVX intrinsics, and the memory used needs to be 32 byte aligned.
Looking at the documentation for the mex memory functions I can't see any specific alignment which is provided by mxCalloc or mxMalloc.
However, running the following example under MATLAB 2014a 64-bit in Linux:
#include <mex.h>
#include <matrix.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
int len;
void *data;
size_t data_addr;
size_t alignment;
alignment = 0;
for (len = 1; len < 0x10001; len++)
{
data = mxMalloc (len);
data_addr = (size_t) data;
alignment |= data_addr;
}
mexPrintf ("mxMalloc alignment=%lx\n", alignment);
alignment = 0;
for (len = 1; len < 0x10001; len++)
{
data = mxCalloc (len, 1);
data_addr = (size_t) data;
alignment |= data_addr;
}
mexPrintf ("mxCalloc alignment=%lx\n", alignment);
}
Appears to show that the addresses returned by mxMalloc and mxCalloc have 32 byte alignment (in that the least significant 5 bits of the addresses are always zero):
>> mex c_align_test.c
Building with 'gcc'.
MEX completed successfully.
>> c_align_test
mxMalloc alignment=7f85ffffffe0
mxCalloc alignment=7f85ffffffe0
Is the guaranteed memory alignment provided by mxCalloc and mxAlloc documented anywhere?
0 Comments
Accepted Answer
James Tursa
on 7 Jul 2014
This topic has come up in the past. I believe the MATLAB API functions use malloc & friends in the background, and those functions are required to return a pointer that is properly aligned for any typical object on the system you are running on. E.g., see a short discussion here:
However, as is pointed out this requirement does not necessarily cover special cases, and your 32-byte alignment would probably fit into that category. I am unaware of any MATLAB documentation that discusses this level of detail to give you the warm fuzzy you want.
More Answers (0)
See Also
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!