gpt4 book ai didi

相对于结构定义位置(和填充)的 C malloc 偏移量

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:44 24 4
gpt4 key购买 nike

C题:

malloc'ing 结构是否总是导致内部数据从上到下的线性放置?作为第二个小问题:填充大小是否有标准,或者它在 32 位和 64 位机器之间有所不同?

使用这个测试代码:

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

struct test
{
char a;
/* char pad[3]; // I'm assuming this happens from the compiler */
int b;
};

int main() {
int size;
char* testarray;
struct test* testarraystruct;

size = sizeof(struct test);
testarray = malloc(size * 4);
testarraystruct = (struct test *)testarray;
testarraystruct[1].a = 123;

printf("test.a = %d\n", testarray[size]); // Will this always be test.a?

free(testarray);
return 0;
}

在我的机器上,大小始终为 8。因此我检查 testarray[8] 以查看它是否是第二个结构的“char a”字段。在这个例子中,我的机器返回 123,但这显然不能证明它总是如此。

C 编译器是否保证结构是按线性顺序创建的?

我并不是说这样做是安全的或正确的,这是一个好奇的问题。

如果变成 C++,这会改变吗?


更好的是,如果将内存分配到 0x00001000,我的内存会像这样吗?

0x00001000 char a      // First test struct
0x00001001 char pad[0]
0x00001002 char pad[1]
0x00001003 char pad[2]
0x00001004 int b // Next four belong to byte b
0x00001005
0x00001006
0x00001007
0x00001008 char a // Second test struct
0x00001009 char pad[0]
0x0000100a char pad[1]
0x0000100b char pad[2]
0x0000100c int b // Next four belong to byte b
0x0000100d
0x0000100e
0x0000100f

注意:这个问题假设 int 是 32 位

最佳答案

  • 据我所知,struct 的 malloc 不是线性放置数据,而是为结构中的成员线性分配内存,当您创建它的对象时也是如此。
  • 这也是填充所必需的。
  • 填充还取决于机器类型(即 32 位或 64 位)。
  • CPU 根据内存是 32 位还是 64 位获取内存。
  • 对于 32 位机器,您的结构将是:

    struct test
    {
    char a; /* 3 bytes padding done to a */
    int b;
    };
  • 这里您的 CPU 获取周期是 32 位,即 4 个字节

  • 所以在这种情况下(对于这个例子)CPU 需要两个获取周期。
  • 为了在一个获取周期内更清晰,CPU 分配了 4 个字节的内存。因此将对“char a”进行 3 个字节的填充。

  • 对于 64 位机器,您的结构将是:

    struct test
    {
    char a;
    int b; /* 3 bytes padding done to b */
    }
  • 这里的 CPU 获取周期是 8 个字节。

  • 因此在这种情况下(对于本示例)CPU 需要一个获取周期。所以这里必须对“int b”进行3个字节的填充。

  • 但是你可以避免填充,你可以使用#pragma pack 1

  • 但这不会是有效的 w.r.t 时间,因为这里的 CPU 获取周期会更多(对于此示例,CPU 获取周期将为 5)。
  • 这是 CPU 获取周期和填充之间的权衡。

关于相对于结构定义位置(和填充)的 C malloc 偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25394800/

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