Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

PORTING.BITFIELDS

Bit fields in a structure

The PORTING checkers identify code that might rely on specific implementation details in different compilers. The PORTING.BITFIELDS checker detects the use of bit fields within a structure.

Vulnerability and risk

When you define a data structure using bit fields, you're relying on the underlying endian representation of a particular compiler on a particular chip in laying out that structure in memory. Moving an application to a different compiler-for instance, for data transmission or persistent storage-can easily modify this layout, resulting in problems when that data structure is projected onto a byte buffer.

Mitigation and prevention

To avoid these porting problems, define specific variants of structures that are explicitly laid out for a particular endian architecture, and guard each variant with the appropriate BIG_ENDIAN or LITTLE_ENDIAN macro.

Vulnerable code example


1   struct
2   {
3       unsigned short f1 : 4;
4       unsigned short f2 : 5;
5       unsigned short f3 : 7;
6   } myPackedLayout;

The problem in this example is that when there's a shift between endian architectures, the runtime layout of the structure can change so that 'f3' occurs either before or after 'f1' depending on the chip and tool chain.

Fixed code example


1   #if BIG_ENDIAN

2   struct
3   {
4      unsigned short f1 : 4;
5      unsigned short f2 : 5;
6      unsigned short f3 : 7;
7   } myPackedLayout;

8   #endif

In this fixed example, we know the layout will always work the same way on chips that share a common architecture, and we can define an alternative packed layout for chips that don't share that architecture. In this case, the layout is defined by the programmer, rather than being dependent on the chip set of the tool chain.

Related checkers