This post will be building off of this one but will be a little more generic.
Often I see pointers to large structs being cast to pointers to smaller structs and I figure that works because the pointers are just the address of the first byte in the structure. What I still have a question about is how to most methods handle pointers when they aren't pointing at the type they expect.
I will use the Socket API as an example:
sockaddr_storage
is larger than sockaddr
but pointers to sockaddr_storage
get cast to pointers to sockaddr
before they are passed to functions like
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
So how to functions tend to handle things when the pointer is pointing to a larger structure than expected. Do they say
"Oh the size (socklen_t addrlen
) passed to me is larger than I thought it would be. Better cast this pointer back to a sockaddr_storage
!"
And then access its members like that? Or do they do something more complex?