我已经广泛使用了结构,并且我已经看到了一些有趣的东西,特别是*value代替value->first_value值是指向struct的指针,first_value是第一个成员,是否*value安全?
另请注意,由于对齐,无法保证大小,基于结构/寄存器大小的alginment值是什么?
我们对齐数据/代码以便更快地执行,我们可以告诉编译器不要这样做吗?那么也许我们可以保证结构的某些东西,比如它们的大小?
当对结构成员进行指针运算以便定位成员偏移时,我认为-如果对大端+进行小端,或者仅仅依赖于编译器吗?
malloc(0)真正分配了什么?
以下代码用于教育/发现目的,并不意味着具有生产质量.
#include <stdlib.h>
#include <stdio.h>
int main()
{
printf("sizeof(struct {}) == %lu;\n", sizeof(struct {}));
printf("sizeof(struct {int a}) == %lu;\n", sizeof(struct {int a;}));
printf("sizeof(struct {int a; double b;}) == %lu;\n", sizeof(struct {int a; double b;}));
printf("sizeof(struct {char c; double a; double b;}) == %lu;\n", sizeof(struct {char c; double a; double b;}));
printf("malloc(0)) returns %p\n", malloc(0));
printf("malloc(sizeof(struct {})) returns %p\n", malloc(sizeof(struct {})));
struct {int a; double b;} *test = malloc(sizeof(struct {int a; double b;}));
test->a = 10;
test->b = 12.2;
printf("test->a == %i, *test == %i \n", test->a, *(int *)test);
printf("test->b == %f, offset of b is %i, *(test - offset_of_b) == %f\n",
test->b, (int)((void *)test - (void *)&test->b),
*(double *)((void *)test - ((void *)test - (void *)&test->b))); // find the offset of b, add it to the base,$
free(test);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
打电话gcc test.c跟着./a.out
我得到这个:
sizeof(struct {}) == 0;
sizeof(struct {int a}) == 4;
sizeof(struct {int a; double b;}) == 16;
sizeof(struct {char c; double a; double b;}) == 24;
malloc(0)) returns 0x100100080
malloc(sizeof(struct {})) returns 0x100100090
test->a == 10, *test == 10
test->b == 12.200000, offset of b is -8, *(test - offset_of_b) == 12.200000
Run Code Online (Sandbox Code Playgroud)
更新 这是我的机器:
gcc --version
i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Run Code Online (Sandbox Code Playgroud)
uname -a
Darwin MacBookPro 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386
Run Code Online (Sandbox Code Playgroud)
从6.2.5/20:
结构类型描述顺序分配的非空成员对象集(并且在某些情况下,是不完整的数组),每个成员对象具有可选地指定的名称并且可能具有不同的类型.
回答:
特别是*值而不是value-> first_value,其中value是指向struct的指针,first_value是第一个成员,*值是否安全?
见6.7.2.1/15:
15在结构对象中,非位字段成员和位字段所在的单元具有按声明顺序增加的地址.指向适当转换的结构对象的指针指向其初始成员(或者如果该成员是位字段,则指向它所在的单元),反之亦然.结构对象中可能存在未命名的填充,但不是在其开头.1
但是,在结构的末尾可能存在填充字节,也可能存在于中间成员之间.
在C中,malloc( 0 )是实现定义的.(作为旁注,这是C和C++不同的小事之一.)
[1]强调我的.
| 归档时间: |
|
| 查看次数: |
3515 次 |
| 最近记录: |