Use assert()

Sadly, very few people do.

What it does is notify you if you reached some logically incorrect state -e.g., if a pointer is NULL, you definitely do not want to continue.

Steps:

include <assert.h>

assert (expression);

// if expression evaluates to false, then the program aborts

// expression can be anything, say (if ptr != NULL)

If the expression does evaluate to false, then you get a message like “assert failed in function foo at line x” – rather useful. Better sprinkle all your code with this – anyway, you can turn it off in production executables by adding

#define NDEBUG

in your code. An easier way – one that doesn’t require source modification – is to pass -DNDEBUG as a parameter when compiling the file.

e.g.,

gcc -c test.c -DNDEBUG

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s