使用 memcmp() 和指针算法比较 C 中的结构

标签 c gcc struct memcmp

我知道 memcmp() 不能用于将尚未被 memset() 的结构与 0 进行比较,因为未初始化的填充。但是,在我的程序中,我有一个开始时有几种不同类型的结构,然后是几十种相同类型,直到结构结束。我的想法是手动比较前几种类型,然后在相同类型成员的剩余连续内存块上使用 memcmp()

我的问题是,C 标准对结构填充有什么保证?我可以在任何或所有编译器上可靠地实现这一点吗? C 标准是否允许在相同类型的成员之间插入结构填充?

我已经实现了我提出的解决方案,它似乎完全按照 gcc 的预期工作:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

struct foo
{
    char a;
    void *b;
    int c;
    int d;
    int e;
    int f;
};

static void create_struct(struct foo *p)
{
    p->a = 'a';
    p->b = NULL;
    p->c = 1;
    p->d = 2;
    p->e = 3;
    p->f = 4;
}

static int compare(struct foo *p1, struct foo *p2)
{
    if (p1->a != p2->a)
        return 1;

    if (p1->b != p2->b)
        return 1;

    return
        /* Note the typecasts to char * so we don't get a size in ints. */
        memcmp(
            /* A pointer to the start of the same type members. */
            &(p1->c),
            &(p2->c),
            /* A pointer to the start of the last element to be compared. */
            (char *)&(p2->f)
            /* Plus its size to compare until the end of the last element. */
            +sizeof(p2->f)
            /* Minus the first element, so only c..f are compared. */
            -(char *)&(p2->c)
        ) != 0;
}

int main(int argc, char **argv)
{
    struct foo *p1, *p2;
    int ret;

    /* The loop is to ensure there isn't a fluke with uninitialized padding
     * being the same.
     */
    do
    {
        p1 = malloc(sizeof(struct foo));
        p2 = malloc(sizeof(struct foo));

        create_struct(p1);
        create_struct(p2);

        ret = compare(p1, p2);

        free(p1);
        free(p2);

        if (ret)
            puts("no match");
        else
            puts("match");
    }
    while (!ret);

    return 0;
}

最佳答案

C 标准对此没有任何保证。从实际的角度来看,它确实是每个当前 C 实现的 ABI 的一部分,并且添加填充似乎没有任何目的(例如,它不能用于检查缓冲区溢出,因为允许符合标准的程序写入填充)。但严格来说它不是“便携”的。

关于使用 memcmp() 和指针算法比较 C 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20623956/

相关文章:

c - 如何在 C 中创建静态 volatile 结构数组?

c - 为什么 gcc 自动矢量化不适用于大于 3x3 的卷积矩阵?

c - Powerpc arch 上的 gcc 内联汇编程序隐式函数声明

c++ - 为什么要在 struct 和 union 上使用 typedef?

c - 如何将嵌套结构体数组作为参数传递给函数?

c++ - 如何将结构作为键插入 map ?

c - 生成的 Bison 解析器的意外行为

C - 写入文件的字符出现次数

c++ - ARM 海湾合作委员会 : Conflicting CPU architectures

gcc - libpthread.so.0 : error adding symbols: DSO missing from command line