C & C++

C & C++

Made by DeepSource

Potentially incorrect memcmp over objects CXX-W2057

Bug risk
Major

Potentially incorrect calls to memcmp() can lead to incorrect comparisons of object representations, especially for non-standard-layout types and types without unique object representations. This can be caused by padding or floating-point types. It is recommended to avoid using object representations for comparisons and instead use special member functions and overloaded operators.

Bad Practice

struct NonStandardLayout {
    int a;
    char b;
    int c;
};

NonStandardLayout obj1{1, 'a', 2};
NonStandardLayout obj2{1, 'a', 3};

int result = memcmp(&obj1, &obj2, sizeof(NonStandardLayout));
// The result may not accurately reflect the differences in the value representations

Recommended

struct NonStandardLayout {
    int a;
    char b;
    int c;

    bool operator==(const NonStandardLayout& other) const {
        return a == other.a && b == other.b && c == other.c;
    }
};

NonStandardLayout obj1{1, 'a', 2};
NonStandardLayout obj2{1, 'a', 3};

bool result = (obj1 == obj2);
// Use a custom operator== function to compare the value representations instead

References