26
typedef union epoll_data
{
  void        *ptr;
  int          fd;
  __uint32_t   u32;
  __uint64_t   u64;
} epoll_data_t;

Here int and __uint32_t are 4 bytes,while the others are 8 bytes.

When we set fd to an int,does it lie on the first 4 bytes or the last 4 bytes,or does it depend on endianness?

Some reason is appreciated.

timrau
  • 22,578
  • 4
  • 51
  • 64
cpuer
  • 7,413
  • 14
  • 35
  • 39

2 Answers2

41

It lies on the first 4 bytes. From the C99 standard §6.7.2.1/14 (§6.7.2.1/16 in C11 and C18):

The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit-field, then to the unit in which it resides), and vice versa.

This implies that the address of all members of a union is the same.

AJM
  • 1,317
  • 2
  • 15
  • 30
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • 1
    Not true, they can start at different locations due to padding. See Figure 3.5 in the ELF standard linked below. It is an example of how order of declaration of fields within a union/structure definition matters. – user209051 Jun 15 '11 at 04:54
  • 9
    @user209051: Wrong. Assuming you meant Figure 3-6 (3-5 is a struct), notice that the bitfields are depicted with low addresses on the right and high addresses on the left. The padding occurs after the members (with higher addresses). – Adam Rosenfield Jun 16 '11 at 04:42
-2

This really depends on ELF-ABI for that platform. See examples and figures give under section 3.1 in http://www.sco.com/developers/devspecs/abi386-4.pdf It shows that it need not start at low address, if there is padding due to alignment constraints.

user209051
  • 309
  • 2
  • 8