Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty "release" ASSERT macro crashes program?

Tags:

c++

macros

Take a look at this code:

#include <cassert>

#ifdef DEBUG
#define ASSERT(expr) assert(expr)
#else
#define ASSERT(expr)
#endif /* DEBUG */

The program will run only if I have DEBUG defined, otherwise it will hang and terminate with no results. I am using MinGW in Eclipse Indigo CDT. Advice is appreciated!

like image 301
AutoBotAM Avatar asked Nov 16 '11 19:11

AutoBotAM


2 Answers

It's hard to tell without looking at the actual code that is causing the issue. My guess: you are evaluating an expression with side-effects within an ASSERT(). For instance, ASSERT( ++i < someotherthing ) whithin a loop. You could confirm by temporary modifying the macro definition to just expr on NDEBUG builds. After confirming this is the cause, go to each and every ASSERT call you are issuing to ensure that the expressions are side-effects free.

like image 121
K-ballo Avatar answered Sep 20 '22 20:09

K-ballo


You are almost certainly abusing assertions. An assertion expression must never have side effects.

When you say, assert(initialize_critical_space_technology());, and then you omit this entire line in the release build, you can imagine for yourself what will happen.

The only safe and sane way to use assertions is on values:

const bool space_init = initialize_critical_space_technology();
assert(space_init);

Some people introduce a VERIFY macro for something that always executes the code:

#define VERIFY(x) (x)         // release
#define VERIFY(x) (assert(x)) // debug
like image 40
Kerrek SB Avatar answered Sep 20 '22 20:09

Kerrek SB