TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
ASML C Coding Standard
Search

Rule:  6.5.8.e

Synopsis:Use memcmp only to compare arrays of scalar types.
Language:C
Severity Level:2
Category:Expressions


Description:

Justification

Compilers add padding bits to structs and unions to have memory alignment. Padding bits are not required to be initialized during struct, union initialization. When comparing two structs with memcmp padding bits are checked too. memcmp result is likely return false even though two structs are the same. Therefore, use memcmp only to compare arrays of scalar types. If you want to compare structs, do a member wise comparison.

Example

struct SimpleStruct
{
  char simple_char;
  /* compiler will add 3 padding bits char[3] */
  int  simple_int;
};

struct SimpleStruct struct1 = {'a',  0};
struct SimpleStruct struct2 = {'a',  0};

/* WRONG, returns 1 (false) in most of the cases */
if( memcmp(&struct1, &struct2, sizeof(struct SimpleStruct) ) == 0)
{
  /* do something */
}

int a[3] = {1, 2, 3};
int b[3] = {1, 2, 3};

/* RIGHT, always returns true */
if( memcmp(&a, &b, sizeof(int) * 3) )
{
  /* do something */
}