C++ Debugging

  1. Using Assertions
  • Assertions are a good mechanism to test the conditions in a program that are expected to be true.
  • If an assert statement fails then program in aborted with a message.
  • This can be used a good source for debugging during development.
  • Asserts can be quietly turned off when production code is to be released.
  • Use “bcc32 -DNDEBUG filename.cpp” to turn off aserts.
  • Alternatively include “define NDEBUG” before #include for assert.h to turn off asserts.

EXAMPLE: Demonstrate the use of asserts for debugging

#include <iostream>//#define NDEBUG#include <assert.h>using namespace std;void main (int argc, char* argv[]){assert ( argc == 3 );int a = atoi(argv[1]);int b = atoi(argv[2]);assert ( a == b );cout << a << endl;cout << b << endl;}INPUT:filename.exe 1OUTPUT:Assertion failed: argc == 3, file assrt.cpp, line 10Abnormal program terminationINPUT:filename.exe 1 2OUTPUT:Assertion failed: a == b, file assrt.cpp, line 15Abnormal program terminationINPUT:filename.exe 1 1OUTPUT:11