.. _assert: ********************** assert() ********************** .. topic:: Learning Outcome Use assert to check invariants and debug. .. topic:: Introduction *assert()* is a macro which tests for conditions which should never occurr in your code. .. topic:: Applicable subjects COMP1511, COMP1521, COMP2521, COMP3231 ---- assert ============== The syntax for assert is: :: assert(); If expression is false, it aborts the program and displays the error to stderr. To use *assert()* place the following at the top of your file: :: #include Disabling asserts ======================= Asserts can dramatically decrease the performance of a system. There are two main ways of disabling asserts: 1. Define debug above the include line for assert : :: #define NDEBUG #include 2. Compile wth the -DNDEBUG flag: :: $ gcc -DNDEBUG -o Uses ======== Common uses of assert include: * Checking for conditions that should never occurr in a correctly running system. * Discovering programming errors * Assert based testing in COMP1511 * Checking that memory has been correctly allocated * To have the system fail in a more controlled manner (rather than abruptly aborting and consuming resources) Cases where asserts should not be used include: * Handling errors (input or otherwise) * Situations in which recovery is required (asserts abort the program) ---- Example ======= We can use *assert()* to check invariants such as whether a pointer is NULL. A common use of assert is to assert that *malloc()* succeeds (it can fail if the computer runs out of memory). If malloc fails, it will return a NULL pointer, which will cause a segmentation fault when it is dereferenced later in the program. Instead we want to make the program fail in a controlled manner, so we use an ASSERT. An example of this is given below: :download:`linked_list.c` .. literalinclude:: linked_list.c :language: c :linenos: :caption: linked_list.c We can run the program :: $ gcc -Wall -Werror -std=c99 -o linked_list linked_list.c $ ./linked_list linked_list: linked_list.c:25: create_node: Assertion `new != NULL' failed. Aborted (core dumped) In this example, malloc fails and returns a NULL pointer which is picked up by the ASSERT. Alternatively, if there was no assert, the program would crash when the program attempts to set the data field. .. moduleauthor:: Liz Willer :Date: 2020-02-14