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 (\[Seacord\]). Variadic functions can also be unsafe because the macros used to process the argument list circumvent the C type system. If care is not exercised when invoking a variadic function to ensure that it knows when to stop processing arguments , the argument it is processing is the right fundamental type, and the argument list is used incorrectly, there may be dangerous and that the argument list is used incorrectly, there may be dangerous consequences. Wiki Markup
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 | ||
---|---|---|
| ||
char const *error_msg = "Resource not available to user."; /* ... */ printf("Error (%s): %s", error_msg); |
Fundamental Types
Some C99 functions, such as printf()
, are implemented as a variadic functions, if care is not taken to ensure that the conversion specifiers to these do not match up with the type of the intended parameter, the result may be abnormal program termination due to alignment errors.
The following code swaps its null terminated byte string and integer parameters with respect to how they were specified in the format string. This means that the integer will be silently casted into a pointer to a null terminated byte string and then dereferenced, possibly causing the program to abnormally terminate (error_message pointer will likewise be silently converted into an integer).
Code Block | ||
---|---|---|
| ||
char const *error_msg = "Error occurred";
/* ... */
printf("%s:%d", 15, error_message);
|
...
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.
...