"It is undefined what will happen if a pointer of some type is converted to void*, and then the void* pointer is converted to a type with a stricter alignment requirement" -C99 rationaleV5.10.pdf
Non-compliant Code Example
char *char_ptr = "example"; int *int_ptr; int *voidPtr2intPtr(void *v_pointer){ return v_pointer; } int_ptr= voidPtr2intPtr(char_ptr);
In this example the pointer might be aligned on a 1 byte boundary. Once it is cast to an int some architectures will require it to be on 4 byte boundaries. Pointers are often cast because a void*
cannot be dereferenced. Careless coding can result in an arbitrary pointer type being used irregardless of its alignment.
Implementation Details
List of common alignments for Microsoft, Borland and GNU compilers to x86
Type |
Alignment |
---|---|
|
1 byte aligned |
|
2 byte aligned |
|
4 byte aligned |
|
4 byte aligned |
|
8 byte on Windows, 4 byte on Linux |
Compliant Solution
-Make specific functions (avoid use of void*) -Always use strictest alignment type for arbitrary pointers.
Risk Assessment
Accessing a pointer that is no longer on the correct access boundary can cause a program to crash, give wrong information or have slow pointer accesses (if the architecture does not care about alignment).
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
DRAFT |
1 (low) |
2 (probable) |
2 (medium) |
P4 |
L3 |
References
Bryant, Randal and O'Hallaron, David. [ 2003 ] 2001 Computer Systems: A Programmer's Perspective. Prentice Hall. ISBN 0-13-034074-X.
- http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf