Suspicious โsizeofโ useยถ
ID: cpp/suspicious-sizeof
Kind: problem
Security severity: 8.8
Severity: warning
Precision: medium
Tags:
- reliability
- correctness
- security
- external/cwe/cwe-467
Query suites:
- cpp-security-extended.qls
- cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
This rule finds expressions that take the size of a function parameter of array type. In C, function parameters of array type are treated as if they had the corresponding pointer type, so their size is always the size of the pointer type (typically either four or eight). In particular, one cannot determine the size of a memory buffer passed as a parameter in this way. Using the sizeof
operator on pointer types will produce unexpected results if the developer intended to get the size of an array instead of the pointer.
Recommendationยถ
Modify the function to take an extra argument indicating the buffer size.
Exampleยถ
void f(char s[]) {
int size = sizeof(s); //wrong: s is now a char*, not an array.
//sizeof(s) will evaluate to sizeof(char *)
}
Referencesยถ
Comp.lang.c, Frequently Asked Questions: Question 6.3: So what is meant by the โequivalence of pointers and arraysโ in C?.
Common Weakness Enumeration: CWE-467.