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

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

 채택된 답변

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

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.
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by