MATLAB: Do I receive an “Assertion failed: Forced Assertion at line 714 of file .\memmgr\m​em32aligne​d.cpp” error message within MATLAB 7.2 (R2006a)

allocatedataforMATLABmemorymxarraynewpointerrealset

I would like to use mxSetPr() to use existing data as the storage for an mxArray, rather than allocating new memory. My MEX-file contains the following code segment:
mxArray * A = mxCreateDoubleMatrix(0, 0, mxREAL);
mxSetM(A, mxGetM(input[0]));
mxSetN(A, mxGetN(input[0]));
mxSetPr(A, mxGetPr(input[0]));
After calling this MEX-file repeatedly, I receive the following error:
Assertion failed: Forced Assertion at line 714 of file ".\memmgr\mem32aligned.cpp".
Corrupted memory block found
[snip]
Stack Trace:
[0] bridge.dll:_mnSignalHandler(0xffffffff, 0, 0, 0x79d8c450) + 350 bytes
[1] bridge.dll:void __cdecl ThrowAssertion(void)(0x01200068, 0x01cc0000, 0x65737341, 0x6f697472) + 152 bytes
[2] bridge.dll:void __cdecl MATLABAssertFcn(char const *,char const *,int,char const *)(0x7849c57c ": Forced Assertion", 0x7849cc08 ".\memmgr\mem32aligned.cpp", 714, 0x7849cfb4 "Corrupted memory block found") + 110 bytes
[3] libut.dll:_mw_malloc32(8, 0x03d0d0a0, 0x00d075f4, 0x7847cd67) + 283 bytes
[4] libut.dll:_mw_calloc32(1, 8, 1, 0x00d07614 ",vÐ") + 17 bytes
[5] libut.dll:_utCalloc(1, 8, 0x03c2f2a0, 0xffffffff) + 119 bytes
[6] libmx.dll:_mxCreateNumericMatrix(1, 1, 6, 0) + 148 bytes
[7] libmx.dll:_mxCreateDoubleScalar(0, 0x40000000, 0xffffffff, 0x433fffff) + 16 bytes
[8] numerics.dll:void __cdecl mfNumberOfElementsFcn(int,struct mxArray_tag * * const,int,struct mxArray_tag * * const)(1, 0x00d0778c, 2, 0x00d076fc) + 352 bytes
[snip]
Error in ==> workspacefunc>num2complex at 234
if isempty(in) || numel(size(in)) > 2 || numel(in) > 10
Error in ==> workspacefunc>getShortValueObjects at 289
ret(i) = getShortValueObject(vars{i});
Error in ==> workspacefunc at 21

Best Answer

This error message is caused by incorrect memory allocation. The mxSetPr() function requires new target memory be allocated in dynamic memory using mxCalloc() or a related function; in particular, you cannot use the data segment of other mxArrays.
To create a second mxArray containing the same data as an existing one, you must copy the data rather than pointing to it. For example:
int Rows = mxGetM(input[0]);
int Cols = mxGetN(input[0]);
mxArray * A = mxCreateDoubleMatrix(Rows, Cols, mxREAL);
double * x = mxGetPr(A);
memcpy(x,mxGetPr(input[0]),Rows*Cols*sizeof(double));
For more information on mxSetPr(), refer to the example listed in the mxSetPr () documentation. From MATLAB, execute the following command:
doc mxSetPr