Matlab eventually crashes on Mex function
Show older comments
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
Answers (1)
James Tursa
on 15 May 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 Comments
DvS
on 16 May 2018
James Tursa
on 16 May 2018
Edited: James Tursa
on 16 May 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?
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) 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!