12.05.06

Visual C++ debug CRTs and assert()

Posted in cplusplus at 8:17 pm by Fernando Cacciola

If your VC++ console application links to a debug CRT, a failed ‘assert()‘ won’t, by default, print a message to stderr and abort(), as you might expect.

But this is a required behaviour for unit testing which naturally needs to run unattended.

After a little inverstigation, I found out how to control what happens when assert() fails (when a debug CRT is used):

int my_report_hook ( int type, char* msg, int* retval )
{
  if ( type == _CRT_ASSERT )
  {
    fprintf(stderr,msg);
    *retval = 0 ;
    abort();
  }
  return TRUE ;
}
_CrtSetReportHook(my_report_hook);

You should know that abort() calls the hook a second time with the ‘type’ argument as ‘_CRT_ERROR’, so make sure to keep the if clause, unless you want to blow up the stack.

Leave a Comment