Versions Compared

Key

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

Different alignments are possible for different types of objects. If the type checking system is overridden by an explicit cast, or the pointer is cast into and out of converted to void * and then to a different type, the alignment of an object may be changed. As a result, if a pointer to one object type is converted to a pointer to a different object type, the objects object types must have the same alignment.

Non-Compliant Code Example

C99 allows a pointer may to be cast into and out of void *. As a result, it is possible to silently convert from one pointer type to another without the compiler diagnosing the problem by storing or casting a pointer to void * and then storing or casting it to the final type. In this non-compliant code example, the type checking system is circumvented due to the caveats of void pointers.

...

This example compiles without warning. However, v_pointer may be aligned on a one byte boundary. Once it is cast to an int *, some architectures will require that the object is aligned on a four byte boundary. If int_ptr is later dereferenced, the program may termination abnormally.terminate abnormally.

One solution would be to ensure that loop_ptr points to an object returned by malloc(), since that is guaranteed to be aligned properly for any need.  However, this is a subtlety that is easily missed when the program is modified in the future.  It is cleaner to let the type system document the alignment needs.

Compliant Solution

Because the input parameter directly influences the return value, and loopFunction() returns an int *, the formal parameter v_pointer is redeclared to only accept int *.

Code Block
bgColor#ccccff
int *loop_ptr;
int *int_ptr;

int *loopFunction(int *v_pointer) {
  return v_pointer;
}
int_ptr = loopFunction(loop_ptr);

Implementation Details

The following list shows common alignments for Microsoft, Borland, and GNU compilers for the IA-32 architecture.

Type

Alignment

char

1 byte aligned

short

2 byte aligned

int

4 byte aligned

float

4 byte aligned

double

8 byte on Windows, 4 byte on Linux

Risk Assessment

Accessing a pointer or an object that is no longer on the correct access boundary can cause a program to crash, give wrong information, or may cause slow pointer accesses (if the architecture does not care about alignmentallows misaligned accesses).

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP36-C

1 (low)

2 (probable)

2 (medium)

P4

L3

Related Vulnerabilities

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

References

Wiki Markup
\[[Bryant 03|AA. C References#Bryant 03]\]
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.2.5, "Types"

...