C / C++ 处理空结构体异同

本文通过实验对比了C和C++编译器对空结构体的处理方式,揭示了不同编译器如何确保每个变量拥有唯一内存地址,并讨论了内存对齐的影响。

闲来无事,尝试下面的代码 :
(64位OpenSuse机器)

#include <stdio.h>

struct Empty
{
};

struct EEmpty
{
    struct Empty e;
    struct Empty e1;
};
int main()
{
    printf("size of Empty struct is : %d\n", sizeof(struct Empty));
    printf("size of EEmpty struct is : %d\n", sizeof(struct EEmpty));
    struct Empty w;
    int a;
    printf("Addr w : %p\n", &w);
    printf("Addr a : %p\n", &a);
    return 0;
}

首先使用GCC编译 :

xxx@WS-TAO0023:gcc c_test.c 
xxx@WS-TAO0023:./a.out 

输出:

size of Empty struct is : 0 
size of EEmpty struct is : 0 
Addr w : 0x7fffe51b9710
Addr a : 0x7fffe51b970c

然后使用G++编译 :

xxx@WS-TAO0023:g++ c_test.c 
xxx@WS-TAO0023:./a.out 

输出:

size of Empty struct is : 1
size of EEmpty struct is : 2
Addr w : 0x7fffa7513b1f
Addr a : 0x7fffa7513b18

可以看到为了保证每个变量(对象) 有唯一的内存地址 :
* C++编译器强制让空结构体大小为1 byte
* C编译器虽然保持空结构体大小为 0 , 但是仍然为它类型的变量分配了空间 .


考虑到内存对齐会导致上面的地址差距大于实际上空结构体占有的内存大小, 对代码进行修改:

    //int a; 替换成下面一行
    char a;

GCC下编译得到 :

size of Empty struct is : 0 byte
size of EEmpty struct is : 0 byte
Addr w : 0x7fff683b6150
Addr a : 0x7fff683b614f

G++下编译得到

size of Empty struct is : 1 byte
size of EEmpty struct is : 2 byte
Addr w : 0x7fff5ce39fef
Addr a : 0x7fff5ce39fee

可见对于空结构体, 大家都只给它最小的1 byte 的内存 .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值