C结构的内部一致性

Spa*_*rky 11 c struct memcmp

如果我有两个C结构初始化为具有相同的成员,我可以保证:

memcmp(&struct1, &struct2, sizeof(my_struct))
Run Code Online (Sandbox Code Playgroud)

永远都会归零?

sim*_*onc 10

我认为你不能安全地用memcmp一个结构来测试平等性.

C11§6.2.6.6类型的表示

当值存储在结构或联合类型的对象中(包括在成员对象中)时,对应于任何填充字节的对象表示的字节采用未指定的值.

这意味着您需要编写一个比较结构中各个元素的函数

int my_struct_equals(my_struct* s1, my_struct* s2)
{
    if (s1->intval == s2->intval &&
        strcmp(s1->strval, s2->strval) == 0 && 
        s1->binlen == s2->binlen &&
        memcmp(s1->binval, s2->binval, s1->binlen) == 0 &&
        ...
        ) {
        return 1;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Pas*_*uoq 9

不,memcmp()由于填充,所有成员相等的两个结构有时可能无法比较相等.

一个似是而非的例子如下.对于初始化st2,符合标准的32位编译器可以生成一系列汇编指令,使最终填充的一部分保持未初始化状态.这段填充将包含堆栈上发生的任何内容,而st1填充通常包含零:

struct S { short s1; long long i; short s2; } st1 = { 1, 2, 3 };
int main() {
  struct S st2 = { 1, 2, 3 };
  ... at this point memcmp(&st1, &st2, sizeof(struct S)) could plausibly be nonzero
}
Run Code Online (Sandbox Code Playgroud)