Saturday, March 2, 2019

My previous post talked about memory management in C and I described how I like to use the assert() function. What I did not note is that assert() functionality can be disabled by defining NDEBUG in the program or passing -DNDEBUG to the compiler. That's a problem if you embed a function call in the expression that you wrap in assert. Let's look at an example.

return EXIT_SUCCESS;}
When compiled, it should probably just print "s: |this is a string|", right? Obviously in a completely unnecessary and complicated way. But that's still what it will do. Let's try (I have saved this code to a file called foop.c):

$ gcc -O0 -g -Wall foop.c$ ./a.outs: |this is a string|

It's a miracle! It worked. But what happens if we compile it with -DNDEBUG?

That's more like it. assert() is useful for developers and I try to make use of it a lot during development, but remember to avoid embedding expressions in what you wrap in assert(). Relying on side effects leads to problems and assert() can't help with that.