Versions Compared

Key

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

Variadic functions provide the ability to specify a variable number of arguments to a function, but they can be problematic. Variadic functions contain an implicit contract between the function writer and the function user that must be made to establish how many arguments are passed on an invocation. If care is not exercised when invoking a variadic function to ensure that it knows when to stop processing arguments and that the argument list is used incorrectly, there may be dangerous consequences.

Argument Processing

In the following code example, a variadic function called average() (taken from an article written by Robert Seacord for Linux World Magazine on variadic functions) is used to determine the average value of its passed integer arguments. The function will stop processing arguments when it sees that the argument is -1.

...

Code Block
bgColor#ffcccc
char const *error_msg = "Resource not available to user.";
/* ... */
printf("Error (%s): %s", error_msg);

Argument List Caveats

C99 functions that themselves that take the variadic primitive va_list pose an additional thread when dealing with variadic functions. Calls to vfprintf(), vfscanf(), vprintf(), vscanf(), vsnprintf(), vsprintf(), and vsscanf() use the va_arg() macro, invalidating the parameterized va_list. Thus, this va_list must not be used except for a call to the va_end() macro once any of those functions are used.

Risk Assessment

Incorrectly using a variadic function can result in abnormal program termination or unintended information disclosure.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL10-A

2 (medium)

2 (probable)

2 (medium)

P8

L2

References

Wiki Markup
\[[ISO/IEC 9899-1999:TC2|AA. C References#ISO/IEC 9899-1999TC2]\] Section 7.15, "Variable arguments"; 7.19.6.8 "The {{vfprintf}} function"