views:

45

answers:

1

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

A: 

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 the re_block struct, for example by casting a pointer to a re_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.

Philip Starhill
The above code is used in a header file and the c code that uses this header accesses the variables of struct as re->re_blocks[0].g = g; re->re_blocks[0].prefix = prefix; re->re_blocks[0].res = 0; re->re_blocks[0].re_hopcnt = 0; re->re_blocks[0].re_node_addr = (u_int32_t)re_node_addr.s_addr; re->re_blocks[0].re_node_seqnum = htonl(re_node_seqnum);
Reno Robert