Memory comparison of padding data
memcmp
compares data stored in structure
padding
Description
This defect occurs
when you use the memcmp
function to compare two
structures as a whole. In the process, you compare meaningless data
stored in the structure padding.
For instance:
struct structType { char member1; int member2; . . }; structType var1; structType var2; . . if(memcmp(&var1,&var2,sizeof(var1))) {...}
Risk
If members of a structure have different data types, your compiler introduces additional
padding for data alignment in memory. For an example of padding, see Higher Estimate of Size of Local
Variables
(Polyspace Code Prover).
The content of these extra padding bytes is meaningless. The
C Standard allows the content of these bytes to be indeterminate,
giving different compilers latitude to implement their own padding.
If you perform a byte-by-byte comparison of structures with memcmp
,
you compare even the meaningless data stored in the padding. You might
reach the false conclusion that two data structures are not equal,
even if their corresponding members have the same value.
Fix
Instead of comparing two structures in one attempt, compare the structures member by member.
For efficient code, write a function that does the comparison member by member. Use this function for comparing two structures.
You can use memcmp
for byte-by-byte comparison
of structures only if you know that the structures do not contain
padding. Typically, to prevent padding, you use specific attributes
or pragmas such as #pragma pack
. However, these
attributes or pragmas are not supported by all
compilers and make your code implementation-dependent. If your structures
contain bit-fields, using these attributes or pragmas cannot prevent
padding.
Examples
Result Information
Group: Programming |
Language: C | C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax: MEMCMP_PADDING_DATA |
Impact: Medium |
Version History
Introduced in R2017a
See Also
Find defects (-checkers)
| Memory comparison of strings
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)