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

Compare with Current View Page History

« Previous Version 17 Current »

When a package variable is declared local, it is often assumed that the package variable's contents are duplicated and stored in the local variable. This is not so; the local variable is set to undef, just like any other uninitialized variable. Consequently, local variables must be initialized. They may be initialized with the contents of the package variable. If they are meant to be uninitialized, they should be explicitly set to undef.

Noncompliant Code Example

This noncompliant code example authenticates the user to enter a password, but only if the $passwd_required variable is defined.

$passwd_required = 1;

# ...

sub authenticate_user {
  local $passwd_required;
  if (defined $passwd_required) {
    print "Please enter a password\n";
    # ... get and validate password
  } else {
    print "No password necessary\n";
  }
}

authenticate_user();

The call to local temporarily sets $passwd_required to the uninitialized value undef; it does not maintain its previous value of 1. Consequently, when the program executes, it incorrectly prints No password necessary.

Compliant Solution

This compliant solution initializes the localized variable to the old value, so it correctly prompts the user for a password.

$passwd_required = 1;

# ...

sub authenticate_user {
  local $passwd_required = $passwd_required;
  if (defined $passwd_required) {
    print "Please enter a password\n";
    # ... get and validate password
  } else {
    print "No password necessary\n";
  }
}

authenticate_user();

Risk Assessment

Uninitialized variables can cause surprising program behavior.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

DCL04-PL

Low

Probable

Medium

P4

L3

Automated Detection

ToolDiagnostic
Perl::CriticVariables::RequireInitializationForLocalVars

Bibliography

 

 
 
 


  • No labels