CXX.ID_VIS.GLOBAL_VARIABLE.STATIC

The CXX.ID_VIS.GLOBAL_VARIABLE.STATIC checker reports a defect when a static global variable is used, read, or written by only one function.

Vulnerability and risk

Defining variables with a wider visibility than required increases the chance the variable will be used accidentally.

Mitigation and prevention

Restrict the scope or visibility of variables as much as possible, to the extent that all required references are possible. For example, if a variable is used by only one function then we can declare the variable as a local variable.

Vulnerable code example

1  static unsigned int a = 0;     // CXX.ID_VIS.GLOBAL_VARIABLE.STATIC //
2  void f0()
3  {
4      if (a++ > 100) return;
5      /* … */
6  }
7  void f1()
8  {
9      /* … */
10 }

In this example, the variable ‘a’ is declared as a static global variable but it is only used in the function f0().

Fixed code example

1  void f0()
2  {
3      static unsigned int a = 0; 
4      if (a++ > 100) return;
5      /* … */
6  }
7  void f1()
8  {
9      /* … */
10 }

Related checkers