Function returns address of local variable in a return

The LOCRET.RET checker finds instances in which a function returns the address of a local variable through an expression in the return statement.

Vulnerability and risk

Local variables are allocated on the stack, so when a function returns a pointer to the variable, it's returning a stack address. The address will be invalidated after returning from the function, so access will probably cause unexpected application behavior, typically a program crash.

Vulnerable code example

  #include <stdlib.h>
  int *func_RET(unsigned n)
      int aux;
      int *p;
      if (n == 1) {
          p = &aux;
      } else {
         p = (int *)malloc(n * sizeof(int));
     return p;

Klocwork flags line 12, indicating that function func_RET returns the address of a local variable through the return statement. The address of local variable aux can be assigned to variable 'p', which is returned.

Related checkers

Security training

Application security training materials provided by Secure Code Warrior.