Versions Compared

Key

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

...

Tool

Version

Checker

Description

LDRA tool suite

Include Page
LDRA_V
LDRA_V

94 S 540 S

Fully implemented
GCC
Include Page
GCC_V
GCC_V
 

Can detect some violations of this rule when the -Wcast-align flag is used.

EDG   
Compass/ROSE  

Can detect violations of this rule. However, it does not flag explicit casts to void * and then back to another pointer type.

ECLAIR

Include Page
ECLAIR_V
ECLAIR_V

castexpr

Fully implemented

Noncompliant Code Example

For objects declared on the stack, The C Standard [ISO/IEC 9899:2011] provides alignas to declare an object to have a stricter alignment. This can be used to resolve the following noncompliant code example.

Code Block
char c = 'x';
int *ip = (int *)&c; /* this can lose information */
char *cp = (char *)ip;
assert(cp == &c);    /* will fail on some conforming implementations */

Compliant Solution

The compliant solution uses alignas to align the the character c to the alignment of an integer. As a result, the two pointers point to equally aligned pointer types.

Code Block
alignas(int) char c = 'x'; /* align c to the alignment of an int */
int *ip = (int *)&c; 
char *cp = (char *)ip;
assert(cp == &c);    /* both cp and &c point to equally aligned objects */

Related Vulnerabilities

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

...

CERT C++ Secure Coding Standard: EXP36-CPP. Do not convert pointers into more strictly aligned pointer types

ISO/IEC 9899:2011 Section 6.2.5, "Types"

ISO/IEC TR 17961 (Draft) Converting pointer values to more strictly aligned pointer types [alignconv]

...