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
Copy
static unsigned int a = 0; // CXX.ID_VIS.GLOBAL_VARIABLE.STATIC //
void f0()
{
if (a++ > 100) return;
/* … */
}
void f1()
{
/* … */
}
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
Copy
void f0()
{
static unsigned int a = 0;
if (a++ > 100) return;
/* … */
}
void f1()
{
/* … */
}
Related checkers
- CXX.ID_VIS.GLOBAL_VARIABLE.EXTERN
- MISRA.VAR.MIN.VIS