You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 43 Next »

The arguments to a macro should not include preprocessor directives, such as #define, #ifdef, and #include. Doing so is undefined behavior, according to subclause 6.10.3, paragraph 11, of the C Standard [ISO/IEC 9899:2011]:

The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of arguments for the function-like macro. The individual arguments within the list are separated by comma preprocessing tokens, but comma preprocessing tokens between matching inner parentheses do not separate arguments. If there are sequences of preprocessing tokens within the list of arguments that would otherwise act as preprocessing directives, the behavior is undefined.

(See also undefined behavior 93 of Annex J.)

The scope of this rule includes using preprocessor directives in arguments to a function where it is unknown whether or not the function is implemented using a macro. For example, standard library functions, such as memcpy(), printf(), and assert(), may be implemented as macros.

Noncompliant Code Example

In this noncompliant code example [GCC Bugs], the author uses preprocessor directives to specify platform-specific arguments to memcpy(). However, if memcpy() is implemented using a macro, the code results in undefined behavior.

#include <string.h>
 
void func(const char *src) {
  /* Validate the source string; calculate size */
  char *dest;
  /* malloc destination string */ 
  memcpy(dest, src,
  #ifdef PLATFORM1
  12
  #else
  24
  #endif
  /* ... */
);

Compliant Solution

In this compliant solution [GCC Bugs], the appropriate call to memcpy() is determined outside the function call:

#include <string.h>

void func(const char *src) {
  /* Validate the source string; calculate size */
  char *dest;
  /* malloc destination string */ 
  #ifdef PLATFORM1
  memcpy(dest, src, 12);
  #else
  memcpy(dest, src, 24);
  #endif

}

Risk Assessment

Improper use of macros may result in undefined behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

PRE32-C

Low

Unlikely

Medium

P2

L3

Automated Detection

Tool

Version

Checker

Description

ECLAIR

1.2

CC2.PRE32

Fully implemented

Related Vulnerabilities

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

Bibliography

[GCC Bugs]"Non-bugs"
[ISO/IEC 9899:2011]Subclause 6.10.3, "Macro Replacement"

 


  • No labels