This program creates and measures a struct with a pointer (8 bytes) and 3 ints (4 bytes each) and shows there are 4 bytes of data padding.
I don’t understand why there are 4 bytes of data padding, either the CPU handles it 8 bytes at a time and there should be another 8 bytes of padding or it handles it 4 bytes at a time and there should be none right?
Or does it stick 2 4 byte values in an 8 byte section of memory and let the CPU split it up at runtime? (This would explain the discrepancy but it seems a bit inefficient to me)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test {
char *name;
int age;
int height;
int weight;
};
struct test *create(char *name, int age, int height, int weight)
{
struct test *thing = malloc(sizeof(struct test));
thing->name = strdup(name);
thing->age = age;
thing->height = height;
thing->weight = weight;
return thing;
}
void destroy(struct test *thing)
{
free(thing->name);
free(thing);
}
int main(int argc, char *argv[])
{
struct test * t1 = create("bleh",1,2,3);
printf("Sizeof struct: %lu\n",sizeof(struct test));
printf("Sizeof pointer (On 64bit system): %lu\n",sizeof(char *));
printf("Sizeof int: %lu\n",sizeof(int));
destroy(t1);
return 0;
}
Output:
Sizeof struct: 24
Sizeof pointer (On 64bit system): 8
Sizeof int: 4
The entire struct is probably padded at the end, for alignment reasons. This is needed since you might want to have an array of this struct.
The padding you mention makes the struct always end up on an address which is evenly divisible by 8.