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.

What Every C Programmer Should Know About Undefined Behavior #1/3

155 pointsby zeugmaabout 14 years ago

6 comments

aidenn0about 14 years ago
I still remember one of my favorite linux bugs was due to the NULL behavior.<p>It was roughly this<p>read-from-p;<p>if(p != NULL) write-to-p;<p>since read-from-p is undefined if p is null, gcc could (and did) legally optimize out the NULL check, so you could end up writing to NULL.<p>[edit] I noticed that this case of bug is actually mentioned in the regehr article that is linked.
评论 #2540498 未加载
评论 #2541124 未加载
jergoshabout 14 years ago
"You don't know. The computer may levitate." is what they used to say in my C course at the uni.
评论 #2542130 未加载
cafabout 14 years ago
<i>It is worth noting that unsigned overflow is guaranteed to be defined as 2's complement (wrapping) overflow, at least by Clang and other commonly available C compilers.</i><p>This is actually guaranteed by the standard (although the language used is not "2s complement", but "repeatedly adding or subtracting one more than the maximum value that can be stored in the type until the value is in range").<p><i>C requires that these sorts of type conversions happen through unions: using pointer casts is not correct and undefined behavior results.</i><p>Actually, loading a member of a union other than the one most recently stored to is undefined behaviour too - it's just that using a union in this way falls into the <i>"...both Clang and GCC nail down a few behaviors that the C standard leaves undefined."</i> category. (And most other compilers besides - there is much historical usage of this).
brimpaabout 14 years ago
It would be nice to have a code snippet for each of the examples. I'm a fairly experienced C++ developer but my knowledge of compilers is, admittedly, lacking and I just want to make sure I'm on the same page.<p>Otherwise, a great read.<p>PS– Is it just me or is LLVM coming up more and more these days?
评论 #2540726 未加载
olovabout 14 years ago
Great article, shame it got optimized away before I had the chance to re-read it.<p>edit: seems Blogger turned their -O knob to eleven <a href="http://status.blogger.com/" rel="nofollow">http://status.blogger.com/</a>
KonradKlauseabout 14 years ago
Why does LLVM generate "ud2" instructions? WTF?
评论 #2540673 未加载