CXX.ID_VIS.GLOBAL_VARIABLE.EXTERN
The CXX.ID_VIS.GLOBAL_VARIABLE.EXTERN checker reports defect when a global variable is used 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
unsigned int a = 0; // CXX.ID_VIS.GLOBAL_VARIABLE.EXTERN //
void f0()
{
if (a++ > 10) return;
/* … */
}
void f1()
{
/* … */
}
In this example, the variable ‘a’ is declared as a global variable but it is only used in the function f0().
Fixed code example
Copy
void f0()
{
static unsigned int a = 0;
if (a++ > 10) return;
/* … */
}
void f1()
{
/* … */
}
In the fixed example, we declare the variable ‘a’ within the scope of the function. Adding the static keyword ensures that the variable is not reset every time f0() is called.
Related checkers
- CXX.ID_VIS.GLOBAL_VARIABLE.STATIC
- MISRA.VAR.MIN.VIS