Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki MarkupCopying data to a buffer that is not large enough to hold that data results in a buffer overflow. While not limited to null-terminated byte strings (NTBS), buffer overflows often occurs when manipulating NTBS data. To prevent such errors, limit copies either through truncation (although consult \[[(see STR03-A. Do not inadvertently truncate a null-terminated byte string]\] for problems that may cause) or, preferably, ensure that the destination is of sufficient size to hold the character data to be copied and the null-termination character.

Non-Compliant Code Example (off-by-one error)

...

Compliant Solution (argv) (strcpy_s())

...

The {{strcpy_s()}} function provides additional safeguards, including accepting the size of the destination buffer as an additional argument \[[argument (see STR07-A. Use TR 24731 for remediation of existing string manipulation code]\]).

Code Block
bgColor#ccccff
int main(int argc, char *argv[]) {
  /* ... */
  char * prog_name;
  size_t prog_size;

  prog_size = strlen(argv[0])+1;
  prog_name = (char *)malloc(prog_size);

  if (prog_name != NULL) {
    if (strcpy_s(prog_name, prog_size, argv[0])) {
      /* Handle strcpy_s() error */
    }
  }
  else {
    /* Couldn't get the memory - recover */
  }
  /* ... */
}

...