01.07.2016 Views

SEI CERT C Coding Standard

tqcylJ

tqcylJ

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Preprocessor (PRE) - PRE31-C. Avoid side effects in arguments to unsafe macros<br />

}<br />

/* ... */<br />

Note the comment warning programmers that the macro is unsafe. The macro can also be renamed<br />

ABS_UNSAFE() to make it clear that the macro is unsafe. This compliant solution, like all<br />

the compliant solutions for this rule, has undefined behavior if the argument to ABS() is equal to<br />

the minimum (most negative) value for the signed integer type. (See INT32-C. Ensure that operations<br />

on signed integers do not result in overflow for more information.)<br />

2.2.3 Compliant Solution<br />

This compliant solution follows the guidance of PRE00-C. Prefer inline or static functions to<br />

function-like macros by defining an inline function iabs() to replace the ABS() macro. Unlike<br />

the ABS() macro, which operates on operands of any type, the iabs() function will truncate arguments<br />

of types wider than int whose value is not in range of the latter type.<br />

#include <br />

#include <br />

static inline int iabs(int x) {<br />

return (((x) < 0) ? -(x) : (x));<br />

}<br />

void func(int n) {<br />

/* Validate that n is within the desired range */<br />

int m = iabs(++n);<br />

}<br />

/* ... */<br />

2.2.4 Compliant Solution<br />

A more flexible compliant solution is to declare the ABS() macro using a _Generic selection.<br />

To support all arithmetic data types, this solution also makes use of inline functions to compute<br />

integer absolute values. (See PRE00-C. Prefer inline or static functions to function-like macros<br />

and PRE12-C. Do not define unsafe macros.)<br />

According to the C <strong>Standard</strong>, 6.5.1.1, paragraph 3 [ISO/IEC 9899:2011]:<br />

The controlling expression of a generic selection is not evaluated. If a generic selection<br />

has a generic association with a type name that is compatible with the type of the controlling<br />

expression, then the result expression of the generic selection is the expression<br />

in that generic association. Otherwise, the result expression of the generic selection is<br />

the expression in the default generic association. None of the expressions from any<br />

other generic association of the generic selection is evaluated.<br />

<strong>SEI</strong> <strong>CERT</strong> C <strong>Coding</strong> <strong>Standard</strong>: Rules for Developing Safe, Reliable, and Secure Systems 26<br />

Software Engineering Institute | Carnegie Mellon University<br />

[DISTRIBUTION STATEMENT A] Approved for public release and unlimited distribution.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!