NShiftKey-Rule-Guide logo NShiftKey-Rule-Guide

1. Vulnerability Description

2. Vulnerability Countermeasure

3. Sample Code

Reference between variables with different lifetime

#include <stdio.h>
  
const char *p;
void dont_do_this(void) {
  const char c_str[] = "This will change";
  p = c_str; /* Dangerous */
}
 
void innocuous(void) {
  printf("%s\n", p);
}
 
int main(void) {
  dont_do_this();
  innocuous();
  return 0;
}
void this_is_OK(void) {
  const char c_str[] = "Everything OK";
  const char *p = c_str;
  /* ... */
}
/* p is inaccessible outside the scope of string c_str */

reference a variable with expired lifetime

void squirrel_away(char **ptr_param) {
  char local[10];
  /* Initialize array */
  *ptr_param = local;
}
 
void rodent(void) {
  char *ptr;
  squirrel_away(&ptr);
  /* ptr is live but invalid here */
}
char local[10];
  
void squirrel_away(char **ptr_param) {
  /* Initialize array */
  *ptr_param = local;
}
 
void rodent(void) {
  char *ptr;
  squirrel_away(&ptr);
  /* ptr is valid in this scope */
}