MATLAB: Do I see strange behavior when I modify the inputs to the MEX file

MATLAB

I am writing a MEX-file and in the MEX-file I am modifying my input to the MEX-file. However, I see strange results, such as the contents of other variables changing that I am not modifying. Why does this happen?

Best Answer

In general, you should not modify the inputs of your MEX-file. The data that is associated with the inputs to the MEX file is cleaned up by the MATLAB memory manager, so touching already allocated memory is not a good idea.
If you would like to use the data that is contained in your input variables, we recommend making a copy of the input with the mxDuplicateArray function. For example:
plhs[0] = mxDuplicateArray(prhs[0]);
Note that the default mexFunction() function header is:
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
The prhs pointer is declared with the "const" keyword, so modifying the data pointed by it is not a good idea.