r0n9
r0n9

Reputation: 2729

c++ socket: size of the structure addrinfo

I am using eclipse with cygwin. The application is 64bit. In cygwin the structure is defined as :

struct addrinfo {
  int             ai_flags;         /* input flags */
  int             ai_family;        /* address family of socket */
  int             ai_socktype;      /* socket type */
  int             ai_protocol;      /* ai_protocol */
  socklen_t       ai_addrlen;       /* length of socket address */
  char            *ai_canonname;    /* canonical name of service location */
  struct sockaddr *ai_addr;         /* socket address of socket */
  struct addrinfo *ai_next;         /* pointer to next in list */
};

The sizeof(addrinfo) result is 48. The size of socketlen_t is 4 bytes. The int type size is 4 bytes. The pointer is 8 bytes in the 64 bits application. The total bytes is 44(4 ints = 16 bytes, socket_len = 4 bytes, 3 pointers = 24; 20+4+24 = 44). I am wondering what the missing 4 bytes for? Are they for padding? I thought 44 bytes do not need to be aligned. Any thought?

Thanks for the answer in advance.

Upvotes: 5

Views: 821

Answers (2)

H. Guijt
H. Guijt

Reputation: 3365

It's padding, after the socklen_t. The next variable in the struct is a pointer, which is 64-bits in length, and will (in this case) be aligned to 64-bits as well. Note however that padding is dependent on architecture and compiler settings; it happens here, but is not guaranteed to always happen.

Note that since you are sharing this struct with the operating system, you should NOT try to change the padding yourself (most compilers allow this using compiler switches and/or pragmas). The OS is expecting this struct with a certain amount of padding included. If you fail to provide it, all the pointers at the end of the struct will have their values misinterpreted.

Upvotes: 4

Tom Chadaravicius
Tom Chadaravicius

Reputation: 393

It's "struct member alignment", the /Zp flag
Data structure alignment,
Microsoft documentation

Upvotes: 2

Related Questions