Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Implicit downcast from bitfield

ID: cpp/implicit-bitfield-downcastKind: problemSecurity severity: Severity: warningPrecision: highTags:   - reliability   - correctness   - typesQuery suites:   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

A bitfield may be unintentionally truncated when implicitly cast to an integer type storing fewer bits. This can lead to inaccurate iteration or allocation when the bitfield is used to count elements of a data structure, or to loss of information stored in the upper portion of the bitfield.

Recommendation

Use the bitfield with a wider integer type, or use an explicit cast if the truncation is intended.

Example

In the following example, a bitfield is accessed both through a method that truncates it and through direct field access. This results in a buffer overflow in the for loop.

typedefstruct{unsignedintx:24;}my_struct;unsignedshortgetX(my_structs){returns.x;//BAD: implicit truncation}unsignedintgetXGood(my_structs){returns.x//GOOD: no truncation}intmain(intargc,char**argv){my_structs;s.x=USHORT_MAX+1;int*array=calloc(sizeof(int),getX(s));//BAD: buffer allocated is smaller than intendedfor(inti=0;i<s.x;i++){array[i]=i;}int*array2=calloc(sizeof(int),getXGood(s));//GOODfor(inti=0;i<s.x;i++){array[i]=i;}}

References


[8]ページ先頭

©2009-2025 Movatter.jp