Matlab eventually crashes on Mex function

I have a Mex function that forwards specific messages and message types (1,2,3) from C to the Matlab function 'fruit_getpar.m'. This Matlab function 'fruit_getpar.m' extracts parameters from the message string and stores it as variables. The C messages are generated at random instances. The problem: Matlab crashes eventually with generated C messages, althuogh the structure of this message is allways the same.
any clues?
#include "mex.h"
#include "fruit_matlab.h"
#include "string.h"
// Callback function
void fruit_mexCallback(char *message, double message_type)
{
mxArray *lhs[2];
char sType[5];
if (message == NULL || message_type <= 0)
return;
if (strstr(message, "apple") == NULL && strstr(message, "banana") == NULL && strstr(message, "orange") == NULL) {
itoa((int)message_type, sType, 10);
lhs[0] = mxCreateString(message);
lhs[1] = mxCreateString(sType);
mexCallMATLAB(0, NULL, 2, lhs, "fruit_getpar");
mxDestroyArray(lhs[0]);
mxDestroyArray(lhs[1]);
}
return;
}
// MEX Gateway
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
//pointer to callback function
void (*cbPtr)() = NULL;
cbPtr = fruit_mexCallback;
Register_Callback(cbPtr);
}
regards, Daan

Respuestas (1)

James Tursa
James Tursa el 15 de Mayo de 2018
Are you sure that message is null terminated, and that sType is large enough? What happens if you do this:
char sType[33];

2 comentarios

DvS
DvS el 16 de Mayo de 2018
Hi James, I will give it a try. Is there a way to check upfront if a message is null terminated (before it actually crashes :P )?
James Tursa
James Tursa el 16 de Mayo de 2018
Editada: James Tursa el 16 de Mayo de 2018
No. If the only thing being passed is the pointer, then the function has to assume that either the pointer is NULL, or if the pointer is not NULL then it contains a null terminated string. It is up to the caller to do this to ensure that the called function does not access invalid memory.
What is the point of these lines?
void (*cbPtr)() = NULL;
cbPtr = fruit_mexCallback;
Why can't you just pass in fruit_mexCallback to your Register_Callback function?

Iniciar sesión para comentar.

Categorías

Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Centro de ayuda y File Exchange.

Productos

Preguntada:

DvS
el 15 de Mayo de 2018

Editada:

el 16 de Mayo de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by