Why do I receive the error "The pointer passed to 'vector_check' is invalid" error when using mxSetPr?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
MathWorks Support Team
am 21 Jun. 2010
Bearbeitet: MathWorks Support Team
am 10 Mai 2023
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
Akzeptierte Antwort
MathWorks Support Team
am 9 Mai 2023
Bearbeitet: MathWorks Support Team
am 10 Mai 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 Kommentare
James Tursa
am 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
am 17 Apr. 2023
Bearbeitet: James Tursa
am 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu External Language Interfaces finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!