3

I'm using the mxAssert-macro defined by matrix.h in my C++ code which mex perfectly compiles. When an assertion is violated in my called mex code, this assertion causes not my program to crash but Matlab itself. Am I missing something out? Is that intended behavior? When I look at Matlab's crash report, the causing assertion is the very same raised by my code - including my descriptive description... Do I have to run my mex code in a certain way so that Matlab can recognize mex code caused assertions (similar to try-catch)? Probably there's another way to safely stop my mex code and return to the Matlab prompt.

Thank you in advance, any help is very appreciated!

EDIT: the code is compiled with the command mex -v Temp.cpp -g

EDIT: a minimal example that brings my matlab to its knees:

#include <matrix.h>
class Temp {
public:
    Temp();
    virtual ~Temp();
};

Temp::Temp() {
    // TODO Auto-generated constructor stub
}

Temp::~Temp() {
    // TODO Auto-generated destructor stub
}

extern "C" {
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    int foo = 10;
    mxAssert(foo==11, "foo is not 10");
}
}
Jav_Rock
  • 22,059
  • 20
  • 123
  • 164
Eric
  • 1,594
  • 1
  • 15
  • 29
  • 1
    This should not happen. Assertion failure should bring you back to the matlab command line. Try a simple minimal mex first and post the code if it still fails. – nimrodm Dec 13 '11 at 18:27

1 Answers1

2

On my system (Ubuntu 64), it crashes too.

I guess it makes senss, because that's what assert is supposed to do.

I strongly advise you to use something like:

if(error){mexErrMsgTxt("assert failed\n");}

Otherwise, one of my friends have the following trick (with preprocessor instructions):

#define assert( isOK )       ( (isOK) ? (void)0 : (void) mexErrMsgTxt("assert failed\n") )

To print individual error strings, e.g. myassert(A=B,"A not B") , you can enhance this a little bit:

#define myassert( isOK,astr )      ( (isOK) ? (void)0 : (void) mexErrMsgTxt(astr) ) 

He also told me that you can improvie it using something like:

#isOK,__LINE__,__PRETTY_FUNCTION__, __FILE__

...in order to print the line number and so on.

JaBe
  • 664
  • 1
  • 8
  • 27
Oli
  • 15,935
  • 7
  • 50
  • 66
  • How is it possible to pass the preprocessor variables like line number etc. to the `mexErrMsgTxt`? – JaBe Feb 19 '15 at 13:57
  • 1
    @JaBe, good question. Maybe you could make a new C++ question about it. – Oli Feb 20 '15 at 13:16
  • yes see: http://stackoverflow.com/questions/28630530/how-to-print-c-preprocessor-variables-like-line-with-mexerrmsgtxt-in-matla – JaBe Feb 20 '15 at 13:49