Versions Compared

Key

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

...

Non-Compliant Code Example

This example could be taken from a file-copying program. It allocates a buffer of user-defined size on the stack to temporarily store data read from the source file.

Code Block

int copy_file(FILE *src, FILE *dst, size_t bufsize)
{
  char buf[bufsize];

  while (fgets(buf, bufsize, src))
    fputs(buf, dst);

  return 0;
}

Compliant Solution

This solution replaces the dynamic array with a call to malloc, and performs appropriate error checking on the malloc return value.

Code Block

int copy_file(FILE *src, FILE *dst, size_t bufsize)
{
  char *buf = malloc(bufsize);
  if (!buf)
    return -1;

  while (fgets(buf, bufsize, src))
    fputs(buf, dst);

  return 0;
}

Recursion

Excessive recursion also requires the kernel to grow the stack, and can thus lead to the process being killed due to lack of memory. Depending on the algorithm, this can be much more difficult to fix than the use of dynamic arrays. However, the use of recursion in most C programs is limited in part because non-recursive solutions are often faster.

...