-3
struct Flat {
  int a1; 
  int a2;
}
// a hierarchical struct which containing a struct attribute
struct NonFlat {
  Flat  b1; 
  int b2;
}

Flat f1, f2;
memcmp (&f1, &f2, sizeof f1) 

in my compiler, it works, meaning

f1.a1 == f2.a1, f1.a2 == f2.a2 <=> memcmp (f1, f2) == 0;

NonFlat n1, n2;
memcmp (&n1, &n2, sizeof n1) // does it also work for non-flat structs, considering the padding?     

I assume it should also work for NonFlat structs. However, in my compiler, for non-flat structs, it seems even though the member attributes are equal, the result of memcmp indicates they are different.

pepero
  • 7,095
  • 7
  • 41
  • 72

2 Answers2

5

The C library function memcmp does a byte-by-byte comparison of memory locations. As @MSalters correctly pointed out, this comparison will include any and all padding bytes.

It does not care whether your structures are flat or non-flat for any definition of flat or not flat. It does not care about or know anything about structure semantics.

If the bytes are equal, it will return true. Otherwise it will return false.

The implication is that, for any structure whose members are laid in contiguously in memory, it will match if all the fields match. For any structure with pointers to other locations in memory, it will not follow those pointers to see if the memory they point to match, but instead only look at the literal address stored in the pointer and see if that matches.

merlin2011
  • 71,677
  • 44
  • 195
  • 329
4

Your structures are flat.

Non-flat structures have pointers.

Also you have not initialise those structures.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127