Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
Allocating single memory block for multiple structures
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Eric Sosman, post: 1712897"] No. Here's the problem: A `struct sockaddr_in' might require stricter alignment than a `struct addrinfo', so just sliding forward by `sizeof(struct addrinfo)' bytes may not arrive at an address where it's legitimate for a `struct sockaddr_in' to begin. You're safe on this one, though, because an array of `char' can begin at any location without concern for alignment issues. Although the code above is not portable and not safe, there is a safe and portable and simple alternative: struct addrstuff { struct addrinfo ai; struct sockaddr_in sa; } *both; both = malloc(sizeof *both + strlen(canonname) + 1); if (both == NULL) crash_and_burn(); both->sa.sin_family = PF_INET; /* etc. */ both->ai.ai_addr = (struct sockaddr *) &both->sa; /* etc. */ both->ai.ai_canonname = (char *)(both + 1); strcpy (both->ai.ai_canonname, canonname); Since the compiler knows the alignment requirement of every type, it knows whether to insert padding bytes in the middle of a `struct addrstuff' so that both elements will be properly aligned. It may also add padding at the very end of a `struct addrstuff' so that everything would remain properly aligned if you decided to allocate an array of them, but from your point of view this is wasted space. It'll probably be a small amount of waste, but if you Really Really want to uglify the code to save those few bytes, you could write both = malloc(offsetof(struct addrstuff, sa) + sizeof(struct sockaddr_in) + strlen(canonname) + 1); ... both->ai.ai_canonname = (char*)(&both->sa + 1); Personally, I don't think this is worth while nowadays. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
Allocating single memory block for multiple structures
Top