NShiftKey-Rule-Guide logo NShiftKey-Rule-Guide

1. Vulnerability Description

2. How to check vulnerability

3. Vulnerability Countermeasure

4. Sample Code

Case of using the free() function to release memory.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
  
enum { MAX_ALLOCATION = 1000 };
 
int main(int argc, const char *argv[]) {
  char *c_str = NULL;
  size_t len;
 
  if (argc == 2) {
    len = strlen(argv[1]) + 1;
    if (len > MAX_ALLOCATION) {
      /* Handle error */
    }
    c_str = (char *)malloc(len);
    if (c_str == NULL) {
      /* Handle error */
    }
    strcpy(c_str, argv[1]);
  } else {
    c_str = "usage: $>a.exe [string]";
    printf("%s\n", c_str);
  }
  free(c_str);
  return 0;
}
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
  
enum { MAX_ALLOCATION = 1000 };
 
int main(int argc, const char *argv[]) {
  char *c_str = NULL;
  size_t len;
 
  if (argc == 2) {
    len = strlen(argv[1]) + 1;
    if (len > MAX_ALLOCATION) {
      /* Handle error */
    }
    c_str = (char *)malloc(len);
    if (c_str == NULL) {
      /* Handle error */
    }
    strcpy(c_str, argv[1]);
  } else {
    printf("%s\n", "usage: $>a.exe [string]");
    return EXIT_FAILURE;
  }
  free(c_str);
  return 0;
}

Case of using the realloc() function to release memory.

#include <stdlib.h>
  
enum { BUFSIZE = 256 };
  
void f(void) {
  char buf[BUFSIZE];
  char *p = (char *)realloc(buf, 2 * BUFSIZE);
  if (p == NULL) {
    /* Handle error */
  }
}
#include <stdlib.h>
  
enum { BUFSIZE = 256 };
  
void f(void) {
  char *buf = (char *)malloc(BUFSIZE * sizeof(char));
  char *p = (char *)realloc(buf, 2 * BUFSIZE);
  if (p == NULL) {
    /* Handle error */
  }
}