为什么日志语句会改变程序的输出?

发布于 2024-07-28 23:23:53 字数 142 浏览 2 评论 0原文

我曾经在一次采访中被问到以下问题,但我一直没有很清楚地回答。 我想知道是否有人知道我可以在哪里了解更多信息,谷歌搜索没有多大帮助:

假设您有一个想要测试的程序。 您添加一条日志语句,突然,产生预期输出的程序停止产生预期输出。 可能发生了什么?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

看轻我的陪伴 2024-08-04 23:23:53

啊哈。 我其实也遇到过这样的情况。

让我们考虑一个程序,该程序有一个正在破坏堆栈的错误。 如果引入日志或打印语句,对日志的调用可能会移动堆栈足以导致其改变行为。

思考如何展示一个例子是一个有趣的问题。 可能最容易用 printf 中的错误格式来做到这一点...

好吧,总的来说,至少有一个示例如下所示。

int parent(){ ... printf("%s\n", itoa(child()));

int child(){
    int num;
    scanf("%d%d", num);  /* notice the format; scanf is going to eat more of the
                           * stack than it should.
                           */
    return num;            /* but this return may unwind the stack successfully. */
}

如果您在 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.

int parent(){ ... printf("%s\n", itoa(child()));

int child(){
    int num;
    scanf("%d%d", num);  /* notice the format; scanf is going to eat more of the
                           * stack than it should.
                           */
    return num;            /* but this return may unwind the stack successfully. */
}

Your case would happen if you insert a printf() just before the return.

黯淡〆 2024-08-04 23:23:53

您的程序可能在并发线程之间存在竞争条件,因此对时间的任何更改都可能会改变程序的行为。

通常这是相反的情况,这更糟糕(所谓的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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文