I am confused why clientIf even though declared as uint32(unsigned int - size 4 bytes), is taking up 8 bytes. I have explicitly printed sizeof(uint32) and that shows 4 bytes.
Can someone throw some insight.
I am running this code on a little endian machine x86.
#include <stdio.h>
#include <string.h>
/* network defines */
typedef char uint8;
typedef short uint16;
typedef unsigned int uint32;
typedef uint32 ipv4Addr;
/*********************** V6 IP ADDRESS **********************************/
typedef struct _v6IpAddr
{
union _Bytes
{
uint8 rbyte[16];
uint16 doublebyte[8];
uint32 wordbyte[4];
long long dwordbyte[2];
}unionv6;
#define dbyte unionv6.doublebyte
#define wbyte unionv6.wordbyte
#define dwbyte unionv6.dwordbyte
#define xbyte unionv6.rbyte
}v6IpAddr;
typedef struct _v6IpAddr uint128;
typedef union _comIpAddr
{
ipv4Addr v4Ip;
v6IpAddr v6Ip;
}comIpAddr;
typedef struct abc
{
/*|*/uint32 clientIf; /*|*/
/*|*/comIpAddr clientIp; /*|*/
/*|*/uint8 mac[6]; /*|*/
/*|*/uint16 zero; /*|*/
}ABC;
void print_bytes(const void *object, size_t size)
{
// This is for C++; in C just drop the static_cast<>() and assign.
const unsigned char * const bytes = object;
size_t i;
printf("[ ");
for(i = 0; i < size; i++)
{
printf("%02x ", bytes[i]);
}
printf("]\n");
}
int main()
{
ABC test;
memset(&test,0,sizeof test);
printf("sizeof test = %u\n", sizeof test);
printf("%d-%d-%d\n", sizeof(uint8), sizeof(uint16), sizeof(uint32));
print_bytes(&test, sizeof test);
test.clientIf = 10;
test.clientIp.v4Ip = 0xAABBCCDD;
print_bytes(&test, sizeof test);
printf("%p-%p-%p\n", &(test.clientIf), &(test.clientIp), &(test.clientIp.v4Ip));
return 0;
}
$ ./a.out
sizeof test = 32
1-2-4
[ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ]
[ 0a 00 00 00 00 00 00 00 dd cc bb aa 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ]
0x7fff113b0780-0x7fff113b0788-0x7fff113b0788 $
Edit:
Why will compiler add padding after clientIf since it is already a multiple of 4 bytes?