TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

The difference between undefined behavior and ill-formed C++ programs

41 点作者 st_goliath10 个月前

4 条评论

rileymat210 个月前
&gt; Avoiding code paths with undefined behavior is something you do all the time.<p>&gt; &#x2F;&#x2F; Check the pointer before using it<p>&gt; if (p != nullptr) p-&gt;DoSomething();<p>I love this example.
layer810 个月前
&gt; Undefined behavior (commonly abbreviated UB) is a runtime concept. If a program does something which the language specified as “a program isn’t allowed to do that”, then the behavior at runtime is undefined<p>Importantly, UB is a runtime condition in the general case, in the sense that it cannot be statically determined (again, in the general case). It may depend on input data, or detecting it may amount to solving the halting problem.<p>A consequence of that is that UB cannot be caught by static tools in the general case without changing the language so that a large class of previously valid programs (i.e. not containing UB) become invalid.
TillE10 个月前
&gt; Visual Studio has an unofficial command line option to help identify certain classes of IFNDR<p>I&#x27;m sure there&#x27;s a good reason why this is hard, but I&#x27;m a little surprised that this isn&#x27;t caught by static analysis. Sure enough, I can&#x27;t get MSVC Code Analysis to complain about the example with different inline functions.
评论 #41150335 未加载
评论 #41151361 未加载
评论 #41150412 未加载
Bjartr10 个月前
&gt; However, if your program avoids the code paths which trigger undefined behavior, then you are safe.<p>This seems incorrect as demonstrated by the other undefined behavior story I read on HN today[1], the tl;dr of which, as I understood it, is since UB is not allowed, the compiler can elide checks that would protect against UB for the sake of optimization since a correct program wouldn&#x27;t have caused the UB in the first place and the compiler doesn&#x27;t have to respect the semantics of incorrect programs.<p>[1] <a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=41146860">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=41146860</a>
评论 #41150072 未加载
评论 #41149867 未加载
评论 #41156665 未加载
评论 #41150187 未加载