CWARN.ALIGNMENTPossible incorrect pointer scalingIn 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 riskIncorrect pointer scaling can cause buffer overflow conditions. Vulnerable code example1 int buffer[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 2 int test1() { 3 char *temp = (char *)buffer; 4 int res = (int) (*(temp+6)); 5 return res; 6 } 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 example1 int buffer[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 2 int test1() { 3 char *temp = (char *)buffer; 4 int res = *((int*)temp+6); 5 return res; 6 } In the fixed example, the coding makes it clear that 'res' refers to the seventh element of 'buffer'. External guidance |