Skip to content

Exercises related to Robust Design Patterns - Part 1

Defense Programming

Global Constants

Global variables should be avoided because they usually lead to thread safety hazards. In any case, they should be declared static, so that access is restricted to a single translation unit.

Exercice 1

Global constants, on the other hand, are not a problem, but declaring them correctly can be tricky. Consider the following code snippet:

static char* kStringList[] = {
  "First",
  "Second",
  "Third",
  NULL
};

How shall one ensure that the list cannot be modified?

The C Standard Library

Parts of the C standard library (and the UNIX and GNU extensions) are difficult to use, so you should avoid them. A number of guidelines clearly ban certain interfaces like Red Hat - Absolutely Banned C Interfaces.

Please check the library documentation before using the recommended replacements. Many of these functions allocate buffers using malloc which your code must deallocate explicitly using free.

Exercice 2

While manipulating strings always use functions that explicitly test argument lengths and not simply functions which not just look for 0 characters for string termination. However, these functions evolved over time, and the lengths mean different things depending on the function:

  1. why one needs to avoid using memcmp for NULL terminated strings?
  2. strncpy does not ensure that the target buffer is null-terminated. How can you ensure that the NULL termination is implemented? Is there a better way?
    char aBuffer[10];
    strncpy(aBuffer, data, sizeof(aBuffer));
    

Defense Programming

Offensive programming, although seemingly opposite in word choice, actually expands upon defensive programming and takes it one step further.

Exercice 3

Read the article about Benefits of Offensive Programming and:

  1. name the benefits (4 items)
  2. cite how this approach can be put into practice (6 items)