Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Incorporate diagnostic tests into your program. One convenient mechanism for this is the   The assert() macro is one convenient mechanism for interactive programs.

The assert macro expands to a void expression:

...

In the following example, the test for integer wrap has been omitted for the on unsigned multiplication based on the assumption that MAX_TABLE_SIZE * sizeof(char *) cannot exceed SIZE_MAX. While we know this is true, it cannot do any harm to codify this assumption.

Code Block
bgColor#ccccff
assert(size <= SIZE_MAX/sizeof(char *));
  table_size = size * sizeof(char *);

Note that this technique may not be suitable for server programs or embedded systems.  A failed assertion could lead to denial of service if a hacker discovered how to trigger it, e.g. if size were in some way derived from client input.  In such situations, a soft failure mode such as writing to a log file is more appropriate.

Code Block
bgColor#ccccff

if (size > SIZE_MAX/sizeof(char *)) {
  fprintf(log_file, __FILE__ ": size %u exceeds SIZE_MAX/sizeof(char *)\n", size);
  size = SIZE_MAX/sizeof(char *);
}
table_size = size * sizeof(char *);

...