use assert

The code below compile and execute fine but will also corrupt memory:

// bad code

int data[10];

// ...

int i=11;

// memory corruption

data[i]=5;

For this situation we can use assert to check array accesses.

The following example is recommended way.

// good code

#include <cassert>

int data[10];

// ...

int i=11;

assert((i>=0) && (i<10));

data[i]=5;

This works but we’ve used the constant 10 in two places(the declaration and the assert). It would be easy for someone to change one and not the other.

One solution to this is to use named constants.

// good code

#include <cassert>

const int DATA_SIZE = 10;

int data[DATA_SIZE];

// ...

int i=11;

assert((i>=0) && (i<DATA_SIZE));

data[i]=5;

One better way to do this is using the data variable itself:

assert((i>=0) && (i<sizeof(data)/sizeof(data[0]));

also you can create a macro or function for code reuse.

attention:assert is invalid with NDEBUG mode.

you can deal this with article verify vs assert

Leave a comment





*