0

Is it right to say the value of CMSG_ALIGN(i) is the minimum value of multiple of 8 and >=i if i is an unsigned int variable?

#include <stdio.h>

int main(void) 
{
    int i;

    for (i=0; i<50; ++i) {
        printf("%d\n", CMSG_ALIGN(i));
    }
}

Output I get:

/*       i              CMSG_ALIGN(i)
 *
 *       0                     0
 *       [1,8]                 8
 *       [9,16]                16
 */
P.P
  • 117,907
  • 20
  • 175
  • 238
hel
  • 581
  • 10
  • 26

1 Answers1

2

Is it right to say the value of CMSG_ALIGN(i) is the minimum value of multiple of 8 and >=i if i is an unsigned int variable?

No. The alignment for a given value is not necessarily 8 on all platforms. If it were to be 8 always, CMSG_ALIGN() wouldn't be necessary at all.

You are probably on a 64-bit system. So it's aligned on 8 byte boundary. But if you run the same code on a 32-bit platform, you would probably see that it's a 4 byte alignment.

Note that CMCG_ALIGN() returns size_t. So %zu is the correct format string to print a size_t value.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Thanks! I test sizeof(struct cmsghdr) and the value is 16. The three members are cmsg_len, cmsg_level and cmsg_type. Why sizeof(struct cmsghdr) is not 12? – hel Jan 08 '16 at 11:37
  • [struct padding](https://en.wikipedia.org/wiki/Data_structure_alignment). This is done for alignment. See: [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) – P.P Jan 08 '16 at 11:39
  • In my question sizeof(struct cmsghdr), In the book the member ‘cmsg_len’ is ‘socklen_t’ , 4B, (total 12B for 3 members)but I find that ‘cmsg_len’ is ‘size_t’ , 8B (total 16B for 3 members)in my system. I use command vi -t cmsghdr in the directory /usr/include – hel Jan 08 '16 at 12:03