Sizeof with side effects¶
ID: cpp/sizeof-side-effectKind: problemSecurity severity: Severity: recommendationPrecision: highTags: - reliability - correctness - external/jsfQuery suites: - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
This rule findssizeof expressions that have a parameter with side-effects.sizeof only uses the type of the parameter, so the parameter will not be evaluated. In the C99 standard, usingsizeof on expressions with dynamic arrays may or may not evaluate the side-effect, so it is better to avoid it completely.
Recommendation¶
Simplify thesizeof parameter to use only the subexpression that is of the type you need.
Example¶
intf(void){inti=0;chararr[20];intsize=sizeof(arr[i++]);//wrong: sizeof expression has side effectcout<<i;//would output 0 instead of 1}
References¶
AV Rule 166,Joint Strike Fighter Air Vehicle C++ Coding Standards. Lockheed Martin Corporation, 2005.
Tutorialspoint - The C++ Programming Language:C++ sizeof Operator