Why do I receive the error "The pointer passed to 'vector_check' is invalid" error when using mxSetPr?

1 view (last 30 days)
I am trying to use "mxSetPr" inside a C# application and it returns the following error:
ERROR: The pointer passed to 'vector_check' is invalid

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 9 May 2023
Edited: MathWorks Support Team on 10 May 2023
This is because you are trying to alter memory that will be allocated and destroyed by MATLAB. The “mxSetPr” function should be use only to replace the initial real values with new ones.
Instead use:
Marshal.Copy(dblTmpArray, 0, Mathworks.mxGetPr(mxPtrTmp), intRows * intCols);
Even a simple function like:
#include "mex.h"
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
double* d = (double*)malloc(100*8);
mxArray* a = mxCreateNumericMatrix( 1, 100, mxDOUBLE_CLASS, mxREAL );
if(a)
{ if(mxGetPr(a))
  {
  mxFree(mxGetPr(a));
  }
  mxSetPr(a, d); }
mexPrintf("end\n");
}
will cause the same.
See the following documentation for additional information on memory management :
  2 Comments
James Tursa
James Tursa on 1 Feb 2017
The information in the link is incomplete with regards to the API function mxArrayToString. This particular function allocates memory, but that memory is NOT on the garbage collection list. If the programmer does not manually free it with mxFree, there will be a permanent memory leak.
James Tursa
James Tursa on 17 Apr 2023
Edited: James Tursa on 17 Apr 2023
UPDATE: The mxArrayToString( ) function behavior has been changed. The memory it allocates in the background in later versions of MATLAB is now on the garbage collection list so it won't cause a memory leak if the user doesn't manually free it.
However, the example code shown above has a permanent memory leak! The proper code would be:
if(a)
{
if( mxGetPr(a) ) mxFree(mxGetPr(a)); // Free the current data pointer first
mxSetPr(a, d);
}
The way the above code is currently written, the memory behind the original mxGetPr(a) pointer is not separately on the garbage collection list, so if you don't free it before you overwrite it with the subsequent mxSetPr( ) call the original data pointer will be lost and the memory will be permanently leaked and can only be recovered by quitting and restarting MATLAB.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming 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!