You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

When a variable, array, or pointer is declared as const, do not attempt to modify it.

The specification of const in variables and parameters implies to a maintainer or caller that, despite knowing some memory location, the code will not modify its content. Although C allows you to remove the specifier using typecasts, doing so violates the implication of the specifier.

Non-compliant Code Example 1

In the following example, the function f is passed a const char pointer. It then typecasts the const specification away, and proceeds to modify the contents.

void f(const char *str, int slen) {
   char *p = (char*)str;
   int i;
   for (i = 0; i < slen && str[i]; i++) {
      if (str[i] != ' ') *p++ = str[i];
   }
}

Non-complaint Code Example 2

In this example, a const int array vals is declared, and then its content is modified by calling memset with the function, leading to values of 0 in the vals array.

const int vals[] = {3, 4, 5};
memset((int*)vals, 0, sizeof(vals));

Consequences

If the object really is constant, the compiler may have put it in ROM or write-protected memory. Trying to modify such an object may lead to a program crash. This could give an attacker a denial of service attack.

References

  • No labels