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 enforce this contract may result in undefined behavior. See undefined behavior 133 141  of Appendix J of C99the C standard.

Argument Processing

In the following code example, the variadic function average() calculates the average value of the positive integer arguments passed to the function [Seacord 2005c]. 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);
}

...

Code Block
bgColor#ffcccc
langc

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

...

Code Block
bgColor#ccccff
langc

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

...

Another common mistake is to use more conversion specifiers than supplied arguments, as shown in this noncompliant coding code example.

Code Block
bgColor#ffcccc
langc

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

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

...

Code Block
bgColor#ccccff
langc

const char *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().

...

section

41 S

section

Tool

Version

Checker

Description

LDRA tool suite

Include Page
LDRA_V
LDRA_V
Section

Partially

Implemented

implemented

Related Guidelines

ISO/IEC 9899:19992011 Section 7.1516, "Variable arguments," and Section 7.1921.6.8, "The vfprintf function"

ISO/IEC TR 24772 "OTR Subprogram Signature Mismatchsignature mismatch"

MISRA Rule 16.1

MITRE CWE: CWE-628, "Function Call with Incorrectly Specified Argumentscall with incorrectly specified arguments"

Bibliography

[Seacord 2005c]

...