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

답변 (1개)

James Tursa
James Tursa 2018년 5월 15일

0 개 추천

Are you sure that message is null terminated, and that sType is large enough? What happens if you do this:
char sType[33];

댓글 수: 2

DvS
DvS 2018년 5월 16일
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 2018년 5월 16일
편집: James Tursa 2018년 5월 16일
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?

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

카테고리

도움말 센터File Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

제품

질문:

DvS
2018년 5월 15일

편집:

2018년 5월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by