在结构内部声明变量后出现分段错误
我目前正在使用网络模拟器 2 开发一个项目。当我在结构 re_block 中添加变量时,程序会编译,但在运行时会出现分段错误。当我将变量声明为静态时,没有运行时错误。有人请解释一下这一点。
struct re_block {
# if __BYTE_ORDER == __BIG_ENDIAN
u_int16_t g : 1;
u_int16_t prefix : 7;
u_int16_t res : 2;
u_int16_t re_hopcnt : 6;
# elif __BYTE_ORDER == __LITTLE_ENDIAN
u_int16_t res : 2;
u_int16_t re_hopcnt : 6;
u_int16_t g : 1;
u_int16_t prefix : 7;
# else
# error "Adjust your <bits/endian.h> defines"
# endif
u_int32_t re_node_addr;
u_int32_t re_node_seqnum;
};
#define MAX_RE_BLOCKS
typedef struct {
u_int32_t m : 1;
u_int32_t h : 2;
u_int32_t type : 5;
u_int32_t len : 12;
u_int32_t ttl : 6;
u_int32_t i : 1;
u_int32_t a : 1;
u_int32_t s : 1;
u_int32_t res1 : 3;
u_int32_t target_addr;
u_int32_t target_seqnum;
u_int8_t thopcnt : 6;
u_int8_t res2 : 2;
struct re_block re_blocks[MAX_RE_BLOCKS];
} RE;
我想在 struct re_block 中添加两个浮点变量。请帮忙
I am currently working on a project using network simulator 2. When I add variable inside the structure re_block, the program compiles but gives me segmentation fault during runtime. When i declare the variable as static there is no runtime error. Someone please explain this.
struct re_block {
# if __BYTE_ORDER == __BIG_ENDIAN
u_int16_t g : 1;
u_int16_t prefix : 7;
u_int16_t res : 2;
u_int16_t re_hopcnt : 6;
# elif __BYTE_ORDER == __LITTLE_ENDIAN
u_int16_t res : 2;
u_int16_t re_hopcnt : 6;
u_int16_t g : 1;
u_int16_t prefix : 7;
# else
# error "Adjust your <bits/endian.h> defines"
# endif
u_int32_t re_node_addr;
u_int32_t re_node_seqnum;
};
#define MAX_RE_BLOCKS
typedef struct {
u_int32_t m : 1;
u_int32_t h : 2;
u_int32_t type : 5;
u_int32_t len : 12;
u_int32_t ttl : 6;
u_int32_t i : 1;
u_int32_t a : 1;
u_int32_t s : 1;
u_int32_t res1 : 3;
u_int32_t target_addr;
u_int32_t target_seqnum;
u_int8_t thopcnt : 6;
u_int8_t res2 : 2;
struct re_block re_blocks[MAX_RE_BLOCKS];
} RE;
I want to add two float variables in struct re_block. Please help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用valgrind等内存调试工具,你能找到代码中出现段错误的地方吗?我的猜测是,有一些运行时代码利用了
re_block
结构的数据布局,例如通过将指针强制转换为re_block
实例来键入(u_int16_t *)
并取消引用作为获取第一个成员的方法,而不是使用运算符->
。将成员添加到结构中可以更改数据的布局,因此使用此类技巧的代码可能会中断。Using a memory debugging tool such as
valgrind
, can you find the place in the code where the segfault occurs? My guess would be that there is some runtime code that takes advantage of the data layout of there_block
struct, for example by casting a pointer to are_block
instance to type(u_int16_t *)
and dereferencing as a means of getting the first member, rather than using the operator->
. Adding members to the struct can change the layout of the data, so code that uses such tricks may break.