ID: cpp/suspicious-pointer-scaling-void Kind: problem Security severity: 8.8 Severity: warning Precision: medium Tags: - security - external/cwe/cwe-468 Query suites: - cpp-security-extended.qls - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
Casting arbitrary pointers into void* and then accessing their contents should be done with care. The results may not be portable.
This query finds pointer arithmetic expressions where a pointer to void (or similar) is then cast to another type and dereferenced.
Recommendation¶
Whenever possible, use the array subscript operator rather than pointer arithmetic. For example, replace
*(p+k)withp[k].Cast to the correct type before using pointer arithmetic. For example, if the type of
pisvoid*but it really points to an array of typedouble[]then use the syntax(double*)p + kto get a pointer to thek’th element of the array.If pointer arithmetic must be done with a single-byte width, prefer
char *tovoid *, as pointer arithmetic onvoid *is a nonstandard GNU extension.
Example¶
char example1(int i) { int intArray[5] = { 1, 2, 3, 4, 5 }; void *voidPointer = (void *)intArray; // BAD: the pointer arithmetic uses type void*, so the offset // is not scaled by sizeof(int). return *(voidPointer + i); } int example2(int i) { int intArray[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int *intPointer = intArray; // GOOD: the offset is automatically scaled by sizeof(int). return *(intPointer + i); }
References¶
Common Weakness Enumeration: CWE-468.