Why do I receive the error "The pointer passed to 'vector_check' is invalid" error when using mxSetPr?
10 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
MathWorks Support Team
le 21 Juin 2010
Modifié(e) : MathWorks Support Team
le 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
Réponse acceptée
MathWorks Support Team
le 9 Mai 2023
Modifié(e) : MathWorks Support Team
le 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 commentaires
James Tursa
le 1 Fév 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
le 17 Avr 2023
Modifié(e) : James Tursa
le 17 Avr 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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur External Language Interfaces dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!