Question: I have written following code in MATLAB:

```
#include <string.h>
#include <stdlib.h>
#include "mex.h"
#include "matrix.h"

void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[]){

    double* x = (double*)malloc(5 * sizeof(*x));
    int k;
    for(k=0;k<5;k++)
        x[k] = k;
    mxArray* p1 = mxCreateDoubleMatrix(5, 1, mxREAL);
    mxSetPr(p1, x);
}

```

I call the function with no input or output. The code really does nothing except initializing some vector. I understand that the code has serious memory leak, but aside from memory leaks, when I call the function, MATLAB closes.

If I replace `malloc` with `mxMalloc`, the code will be executed with no problem.
I understand that using mx\* for allocating memory is preferable, but I am sure that malloc and calloc along with free can be used in MEX with no problem.

I also removed (double\*), but still it crashes. 

It is appreciated if let me know why the mentioned code results in MATLAB crashing.
Thanks

Answer: 
First things first, *don't* cast the return value of `malloc` (in C anyway, C++ is a different matter), *especially* if you're not including stdlib.h - you'll run into all sorts of problems in environments where your integers and pointers are different sizes.

Take off the cast and see if it complains about assigning an `int` to a `double *`.

If it does, make sure you include `stdlib.h` to get the `malloc` prototype.

---

In any case, the [documentation](http://www.mathworks.com.au/help/matlab/apiref/mxsetpr.html) is clear:

> 
> The array must be in dynamic memory; call `mxCalloc` to allocate this memory. Do not use the ANSI C `calloc` function, which can cause memory alignment issues leading to program termination.
> 
> 
> 

Although that specifically only mentions the `calloc` functions, the [`mxMalloc` documentation](http://www.mathworks.com.au/help/matlab/apiref/mxmalloc.html) states:

> 
> `mxMalloc` allocates contiguous heap space sufficient to hold `n` bytes. Use `mxMalloc` instead of the ANSI C `malloc` function to allocate memory in MATLAB applications.
> 
> 
> 

Hence, what you're doing is explicitly forbidden by the documentation. Stop doing it. Don't make me come over there :-)

---

For further information, there's quite a bit of information floating around re MatLab's use of things like SIMD for high speed math.

SIMD may require more stringent alignment than what regular C data types require (and hence more stringent than what `malloc` guarantees).

This may well be what's causing your issues, and is supported by the "which can cause memory alignment issues" comment in the documentation. I'm not *totally* certain that this is the case (since I have no access to MatLab's source code), but it's a viable explanation at least.
To save someone else potential hours of pain, a function using mxMalloc(x) on an input parameter x will only work if x is declared as const int x, as opposed to merely int x.