Versions Compared

Key

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

Variadic functions 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 in any particular invocation. Failure to exercise care when invoking a variadic function to ensure that it knows when to stop processing arguments enforce this contract may result in undefined behavior. See undefined behavior 141 of Appendix J of the C Standard.

Argument Processing

Wiki MarkupIn the following code example, the variadic function {{average()}} is used to determine the average value of its passed positive integer arguments \[[Seacord 05c|AA. C References#Seacord 05c]\]. The function processes arguments until it finds one with a value of {{va_eol}} ({{\-1}} calculates the average value of the positive integer arguments passed to the function [Seacord 2013]. The function processes arguments until it encounters an argument with the value of va_eol (-1).

Code Block

enum { va_eol = -1 };

unsigned int average(int first, ...) {
  unsigned int count = 0;
  unsigned int sum = 0;
  int i = first;
  va_list args;

  va_start(args, first);

  while (i != va_eol) {
    sum += i;
    count++;
    i = va_arg(args, int);
  }

  va_end(args);
  return(count ? (sum / count) : 0);
}

Note that va_start() must be called to initialize the argument list and that va_end() must always be called when finished with a variable argument list.

...

Noncompliant Code Example

In this non-compliant noncompliant code example, the average() function above is called as follows:

Code Block
bgColor#ffcccc
langc

int avg = average(1, 4, 6, 4, 1);

The omission of the va_eol terminating value means that the function will continue to process values from the stack until it encounters a va_eol by coincidence or an error occurs.

Compliant Solution

The following call maintains This compliant solution enforces the contract by adding a va_eol as the last final argument.:

Code Block
bgColor#ccccff
langc

int avg = average(1, 4, 6, 4, 1, va_eol);

...

Noncompliant Code Example

Another common mistake is to use more format conversion specifiers than supplied arguments. This results in undefined behavior, for example, extracting non-existent arguments off the stack and unintentionally exposing data. The following example illustrates this, as shown in this noncompliant code example:

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

This code results in nonexistent arguments being processed by the function, potentially leaking information about the process.

Compliant Solution

The following code This compliant solution matches the number of format specifiers with the number of variable arguments.:

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

Argument List Caveats

C99 C 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 without a call to va_end() followed by a call to va_start().

Risk Assessment

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

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

DCL10-

A

C

high

High

probable

Probable

high

High

P6

L2

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.15, "Variable arguments," and Section 7.19.6.8, "The {{vfprintf}} function"
\[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\] "OTR Subprogram Signature Mismatch"
\[[MISRA 04|AA. C References#MISRA 04]\] Rule 16.1
\[[Seacord 05c|AA. C References#Seacord 05c]\]

Automated Detection

Tool

Version

Checker

Description

Astrée
Include Page
Astrée_V
Astrée_V

Supported, but no explicit checker
Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C0185, C0184
Klocwork
Include Page
Klocwork_V
Klocwork_V
SV.FMT_STR.PRINT_PARAMS_WRONGNUM.FEW
SV.FMT_STR.PRINT_PARAMS_WRONGNUM.MANY
SV.FMT_STR.SCAN_PARAMS_WRONGNUM.FEW
SV.FMT_STR.SCAN_PARAMS_WRONGNUM.MANY

LDRA tool suite
Include Page
LDRA_V
LDRA_V

41 S

Enhanced Enforcement

Parasoft C/C++test

Include Page
Parasoft_V
Parasoft_V

CERT_C-DCL10-aThe number of format specifiers in the format string and the number of corresponding arguments in the invocation of a string formatting function should be equal
PC-lint Plus

Include Page
PC-lint Plus_V
PC-lint Plus_V

558, 719

Assistance provided: reports issues involving format strings

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C: Rec. DCL10-C


Checks for format string specifiers and arguments mismatch (rec. partially covered)

Related Guidelines

ISO/IEC TR 24772:2013Subprogram Signature Mismatch [OTR]
MISRA C:2012Rule 17.1 (required)
MITRE CWECWE-628, Function call with incorrectly specified arguments

Bibliography

[Seacord 2013]Chapter 6, "Formatted Output"


...

Image Added Image Added Image AddedDCL09-A. Declare functions that return an errno error code with a return type of errno_t      02. Declarations and Initialization (DCL)       DCL11-A. Understand the type issues associated with variadic functions