CWARN.ALIGNMENT
Possible incorrect pointer scaling
In C and C++, it's possible to accidentally refer to the wrong memory due to the way math operations are implicitly scaled. The CWARN.ALIGNMENT checker searches for instances in which a pointer may not be correctly aligned.
Vulnerability and risk
Incorrect pointer scaling can cause buffer overflow conditions.
Vulnerable code example
int buffer[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int test1() {
char *temp = (char *)buffer;
int res = (int) (*(temp+6));
return res;
}
In this example, Klocwork issues a CWARN.ALIGNMENT warning at line 4, because there is possible incorrect pointer scaling. In this line, 'res' is probably intended to get the seventh element of array 'buffer', but adding six to the variable 'temp' adds only six bytes. In this case, the integer value is extracted from the middle of third element of 'buffer'.
Fixed code example
int buffer[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int test1() {
char *temp = (char *)buffer;
int res = *((int*)temp+6);
return res;
}
In the fixed example, the coding makes it clear that 'res' refers to the seventh element of 'buffer'.
External guidance
Security training
Application security training materials provided by Secure Code Warrior.