The macros associated with the use parameters of variadic functions implicitly use the parameterized type to determine how many bytes should be pulled for the argument. If the the type is inconsistent with how it is used, a variadic function are interpreted by the va_arg()
macro. va_arg()
is used to pull the next argument from an initialized argument list, the size of which is determined by the parameterized type
. If type
is inconsistent with what was the original parameter to the variadic function, the behavior is undefined and misinterpreted data or an alignment error (see EXP36-C. Do not cast between pointers between objects or types with differing alignments) could result.
Therefore, correct typing must always be maintained when using variadic functions.
Non-Compliant Code Example 1
For example, 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 or misinterpreted data.
...
The following non-compliant 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 is 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 is likewise be silently converted into an integer).
...
Because a long long
was not interpreted, if the architecture is set up in a way that long long
uses more bits for storage, the subsequent format specifier %s
will be is unexpectedly offset, causing unknown data to be used instead of the pointer to the message.
...