Is the memory alignment by mxCalloc and/or mxMalloc defined

3 views (last 30 days)
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?

Accepted Answer

James Tursa
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.
  1 Comment
Chester Gillon
Chester Gillon on 8 Jul 2014
I haven't been able to find anything else which gives the level of detail of the MATLAB memory alignent. However did find that:
1) The MEX functions mxAlloc / mxCalloc end up calling malloc / calloc to perform the allocation.
2) MATAB 2014a under Linux 64-bit uses libstdc++.so.6.0.17 from gcc-4.7.2
3) A C program compiled using the native gcc-4.4.7 gives an alignment of 16 bytes for malloc / calloc
Therefore, I think that later version of glibc may have increased the default alignment to allow for SSE / AVX vector datatypes. e.g. see the discussion on https://gcc.gnu.org/bugzilla/show_bug.cgi?id=15795

Sign in to comment.

More Answers (0)

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!