gpt4 book ai didi

c - 没有与 GCC 的内存对齐

转载 作者:太空狗 更新时间:2023-10-29 15:26:50 24 4
gpt4 key购买 nike

我正在处理一些数据包数据。我已经创建了结构来保存数据包数据。这些结构由 python 为特定的网络协议(protocol)生成。

问题是由于编译器对齐结构,当我通过网络协议(protocol)发送数据时,消息最终比我想要的要长。这会导致其他设备无法识别该命令。

有没有人知道可以解决这个问题,以便我的加壳器恰好是结构应该的大小,或者有什么方法可以关闭内存对齐?

最佳答案

在 GCC 中,您可以使用 __attribute__((packed))。现在 GCC 也支持 #pragma pack

  1. attribute documentation
  2. #pragma pack documentation

例子:

  1. 属性方法:

    #include <stdio.h>

    struct packed
    {
    char a;
    int b;
    } __attribute__((packed));

    struct not_packed
    {
    char a;
    int b;
    };

    int main(void)
    {
    printf("Packed: %zu\n", sizeof(struct packed));
    printf("Not Packed: %zu\n", sizeof(struct not_packed));
    return 0;
    }

    输出:

    $ make example && ./example
    cc example.c -o example
    Packed: 5
    Not Packed: 8
  2. pragma pack 方法:

    #include <stdio.h>

    #pragma pack(1)
    struct packed
    {
    char a;
    int b;
    };
    #pragma pack()

    struct not_packed
    {
    char a;
    int b;
    };

    int main(void)
    {
    printf("Packed: %zu\n", sizeof(struct packed));
    printf("Not Packed: %zu\n", sizeof(struct not_packed));
    return 0;
    }

    输出:

    $ make example && ./example
    cc example.c -o example
    Packed: 5
    Not Packed: 8

关于c - 没有与 GCC 的内存对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18341540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com