In the following code I define a structure header of 9 bytes and it's alligned to the size of 16 bytes. Then I dynamically allocate 9 bytes from heap and assign it to the header pointer.
struct header
{
uint8_t chunk_id;
long int format;
};
int main()
{
std::cout << "sizeof(header) " << sizeof(header) << '\n';
auto head = (header*)malloc(9);
head->chunk_id =3;
head->format=5;
std::cout << (int)head->chunk_id << " " << head->format << '\n' << sizeof(*head);
free(head);
return 0;
}
Output:
sizeof(header) 16
3 5
16
As it turns out, sizeof still informs that this object is 16 bytes (it's 9 though). I guess it just looks at struct's definition. But how does everything work (including operator '->'), when sizeof's size and the actual object size don't match?