Versions Compared

Key

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

...

Code Block
bgColor#ccccff
char dest[ARRAY_SIZE];
char src[ARRAY_SIZE];
size_t i;
/* ... */
for (i=0; src[i] && (i < sizeof(dest)-1); i++) {
  dest[i] = src[i];
}
dest[i] = '\0';
/* ... */

Non-Compliant Code Example (

...

argv )

Arguments read from the command line are stored in process memory. The function main(), called at program startup, is typically declared as follows when the program accepts command-line arguments:

...

Code Block
bgColor#FFcccc
int main(int argc, char *argv[]) {
  /* ... */
  char prog_name[128];
  strcpy(prog_name, argv[0]);
  /* ... */
}

Compliant Solution (

...

argv )

Wiki Markup
The {{strlen()}} function can be used to determine the length of the strings referenced by {{argv\[0\]}} through {{argv\[argc-1\]}} so that adequate memory can be dynamically allocated:

...

Remember to add a byte to accommodate the null-terminated byte string.

Non-Compliant Code Example (

...

argv TOCTOU)

While the above example is secure, the more generic case where the source string is changeable is vulnerable to a TOCTOU race condition.

...

To avoid this problem, use memcpy() or strcpy_s() as described below.

Compliant Solution (argv) (strcpy_s())

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

...

The strcpy_s() function can also be used with a fixed-size statically allocated array. If insufficient space is available strcpy_s() will return an error.

Compliant Solution (argv) (memcpy())

The memcpy() function can provide the same functionality for this example as strcpy_s(), but is more universally available.

...

Code Block
bgColor#FFcccc
/* ... */
char buff[256];
if (getenv("EDITOR") != NULL) {
  strcpy(buff, getenv("EDITOR"));
} else {
  /* No EDITOR environment variable! */
}
/* ... */

Compliant Solution

...