TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

The Lost Art of C Structure Packing

13 pointsby djuliusabout 10 years ago

4 comments

krylonabout 10 years ago
A couple of years back, I ran into a nasty problem with structure packing that made me get acquainted with structure padding and packing.<p>The company I was working at used the OpenWatcom compiler that lets you tune structure padding with a compiler flag. Also, they &quot;serialized&quot; their data by simply writing arrays of structs to files and reading them back in later. Raw binary files, no conversion whatsoever.<p>So one day - I hadn&#x27;t been there very long - I was given the task to make a certain change to the application, as well as a copy of a &quot;database&quot; to experiment on. I made a first adjustment, compiled my code, ran it and - BAM! It took me nearly a day to figure out that I had &quot;forgotten&quot; to pass a certain variable to make which in turn resulted in a certain parameter being passed to the Watcom compiler that caused it to use no structure padding at all.<p>Without that variable&#x2F;parameter, I had compiled the program to use a different padding (i.e. use padding at all), so when my program read the data file (having been dumped by a version of the program being compiled without padding), it barfed, so to speak.<p>That problem caused me to do a little reading on the matter. I sure wish somebody had pointed that article out to me back then. (Assuming it had existed back then, with &quot;back then&quot; being about October 2007.)
pcmonkabout 10 years ago
This is a good article that comes up every so often. If you haven&#x27;t read it, you should. The art is not quite as lost as advertised, though. A lot of C programmers pack structures that way out of habit.<p>There&#x27;s definitely some cases where you shouldn&#x27;t follow the &quot;biggest to smallest&quot; ordering, but they&#x27;re usually pretty obvious when you run into them. They usually involve inheritance and such.
Mithalduabout 10 years ago
In the example in part 4, doesn&#x27;t this:<p><pre><code> char *p; &#x2F;* 8 bytes *&#x2F; long x; &#x2F;* 8 bytes *&#x2F; char c; &#x2F;* 1 byte *&#x2F; </code></pre> Just end up being this, to align whatever comes after it in memory?<p><pre><code> char *p; &#x2F;* 8 bytes *&#x2F; long x; &#x2F;* 8 bytes *&#x2F; char c; &#x2F;* 1 byte *&#x2F; char pad[7]; &#x2F;* 7 bytes *&#x2F;</code></pre>
sctbabout 10 years ago
Recent discussion: <a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=9069031" rel="nofollow">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=9069031</a>