Variadic functions can accept a variable number of arguments, but are problematic. Variadic functions define an implicit contract between the function writer and the function user that allows the function to determine the number of arguments passed passed in any particular invocation. Failure to exercise care when invoking a variadic function to ensure that it knows when to stop processing arguments may result in undefined behavior.
...
Note that va_start()
must be called to initialize the argument list and va_end()
must always be called when finished with a variable argument list.
Non-Compliant Code Example
If However, if the function above is called as follows:
Code Block | ||
---|---|---|
| ||
int avg = average(1, 4, 6, 4, 1); |
The omission of the -1
terminating value means that the function will continue to process values from the stack until it encounters a -1
by coincidence or an error occurs.
Compliant Solution
The following call maintains the contract by adding a -1 as the last argument.
Code Block | ||
---|---|---|
| ||
int avg = average(1, 4, 6, 4, 1, -1);
|
Non-Compliant Code Example
Another common mistake is to use more format specifiers than supplied arguments. This results in undefined behavior, which could end up pulling extra values off the stack and unintentionally exposing data. The following example illustrates a case of this:
Code Block | ||
---|---|---|
| ||
const char *error_msg = "Resource not available to user."; /* ... */ printf("Error (%s): %s", error_msg); |
Compliant Solution
The following code matches the number of format specifiers with the number of variable arguments.
Code Block | ||
---|---|---|
| ||
const char *error_msg = "Resource not available to user.";
/* ... */
printf("Error: %s", error_msg);
|
Argument List Caveats
C99 functions that accept the variadic primitive va_list
as an argument pose an additional risk. Calls to vfprintf()
, vfscanf()
, vprintf()
, vscanf()
, vsnprintf()
, vsprintf()
, and vsscanf()
use the va_arg()
macro, invalidating the parameterized va_list
. Consequently, once a va_list
is passed as an argument to any of these functions, it cannot be used again except in without a call to the va_end()
macro followed by a call to va_start()
.
Risk Assessment
Incorrectly using a variadic function can result in abnormal program termination or unintended information disclosure.
...