为什么日志语句会改变程序的输出?
我曾经在一次采访中被问到以下问题,但我一直没有很清楚地回答。 我想知道是否有人知道我可以在哪里了解更多信息,谷歌搜索没有多大帮助:
假设您有一个想要测试的程序。 您添加一条日志语句,突然,产生预期输出的程序停止产生预期输出。 可能发生了什么?
I was once asked during an interview the following question, and I've still never been quite clear on the answer. I was wondering if anyone knew where I could learn more, googling hasn't been much help:
Say you have a program that you'd like to test. You add a single log statement and suddenly, the program which was producing expected output stops producing expected output. What could have happened?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
啊哈。 我其实也遇到过这样的情况。
让我们考虑一个程序,该程序有一个正在破坏堆栈的错误。 如果引入日志或打印语句,对日志的调用可能会移动堆栈足以导致其改变行为。
思考如何展示一个例子是一个有趣的问题。 可能最容易用 printf 中的错误格式来做到这一点...
好吧,总的来说,至少有一个示例如下所示。
如果您在 return 之前插入 printf() ,就会发生这种情况。
Aha. I've actually had this happen.
Let's consider a program that has a bug that is munging the stack. If you introduce a log or print statement, the call to the log may shift the stack enough to cause it to change behaviour.
It's an interesting problem to think how to show an example. Probably easiest to do it with a bad format in a printf...
okay, in outline at least an example will look like this.
Your case would happen if you insert a
printf()
just before the return.您的程序可能在并发线程之间存在竞争条件,因此对时间的任何更改都可能会改变程序的行为。
通常这是相反的情况,这更糟糕(所谓的Heisenbug):你的程序行为不当,你想通过添加日志输出来调试它。 但日志输出使问题消失,因此诊断变得非常困难。
Your program might have race conditions between concurrent threads, so any change to the timing may change the program behaviour.
Usually this is the other way round, which is much worse (the so called Heisenbug): Your program misbehaves and you want to debug it by adding log output. But the log output makes the problem go away, so it becomes very hard to diagnose.