The scope of a variable determines its “life”, value at a point in execution, and the ability to access it.
A variable can be-
- Local – declared, initiated, and referenced within a function
- Global – declared alongside program headers, outside all functions; can be accessed from all modules
- Parametric – these variables are passed from one function to another as input. If they are passed-by-reference, they are generally global in nature or exists beyond the scope of the function. If they are passed-by-value two copies of them exist, one in the calling function, and the other in the function that receives them.
int g = 0; /*g => global variable */
int add(int x, int y) /* x and y => call-by-value parametric variables */
int sum = 0; /* local variable */
sum = x + y;
int a = 10; /* local variable */
int b = 7;
g = add(a, b);
It is crucial to consider the scope of the variables while planning for security as-
- Global variables are “alive” during the entire program’s execution, making them “susceptible to attack”
- Passing parametric variable by reference shares memory spaces between modules, and makes it vulnerable to memory exploitation hacks
Scope minimization helps developers avoid common programming errors and improves code readability by connecting the declaration and actual use of a variable, and improves maintainability because unused variables are more easily detected and removed.