Comparing structs

This little quiz explores the pitfalls of trying to compare structs. Do you know the right way to check if two structs are the same?

Question: What is the value of bSame and why?

#include <cstring>

struct S
   float f;
   char c;
   int i;

int main()
   S s1 = { 1.1f, 'a', 99 };
   S s2 = { 1.1f, 'a', 99 };

   bool bSame = memcmp(&s1, &s2, sizeof(S)) == 0;

Answer: The value of bSame is undefined.


The reason is that compilers are allowed to put padding into struct and class types for data alignment to preserve word boundary alignment and for efficiency reasons they are not obliged to initialize this padding to any specific value. This being the case the result will be compiler specific and, therefore, undefined.

This code is not portable and although it might work on your compiler or even your specific version of the build (for example, in a debug build in Visual Studio the compiler does null out structures to facilitate debugging) there is no guarantee this will work on other platforms or other compilers.

You can mitigate this by using memset to nullify the memory first but this should be avoided on non POD types as it can have unexpected side effects (such as obliterating the v-table of a class with virtual functions). In short, the only safe way to compare structures is to perform a member by member comparison (preferably by adding the comparison operators).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.