c++递增 unsigned long int 时崩溃

发布于 2024-10-24 19:27:39 字数 294 浏览 2 评论 0原文

这就是WTF城市。

下面的程序在几千次循环后崩溃了。

unsigned long int nTurn = 1;
bool quit = false;

int main(){
    while(!quit){
        doTurn();
        ++nTurn;
    }
}

当然,这是从我的游戏中简化的,但 nTurn 目前除了增量之外没有任何地方使用,当我注释掉 ++nTurn 行时,程序将可靠地永远循环。不应该是几百万吗?

WTF,堆栈溢出?

This one is WTF city.

The below program is crashing after a few thousand loops.

unsigned long int nTurn = 1;
bool quit = false;

int main(){
    while(!quit){
        doTurn();
        ++nTurn;
    }
}

That's, of course, simplified from my game, but nTurn is at the moment used nowhere but the incrementing of it, and when I comment out the ++nTurn line, the program will reliably loop forever. Shouldn't it run into the millions?

WTF, stackoverflow?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

柠北森屋 2024-10-31 19:27:39

你的问题在别处。

程序的其他部分正在从最终指向 nTurn 的通配指针读取数据,当此循环更改值时,其他代码的行为会有所不同。或者存在竞争条件,并且增量使该循环花费的时间稍微长一点,因此竞争的事情不会造成麻烦。在其他地方你可能会犯很多错误。

你能在 valgrind 下运行你的程序吗?有些错误它不会发现,但很多错误它会发现。

Your problem is elsewhere.

Some other part of the program is reading from a wild pointer that ends up pointing to nTurn, and when this loop changes the value the other code acts different. Or there's a race condition, and the increment makes this loop take just a tiny bit longer so the race-y thing doesn't cause trouble. There are an infinite number of things you could have wrong elsewhere.

Can you run your program under valgrind? Some errors it won't find, but a lot it will.

巡山小妖精 2024-10-31 19:27:39

可能听起来很愚蠢,但是,如果我正在看这个,我可能会输出 nTurn var 并查看它是否总是在该值上崩溃。然后,也许将 nTurn 初始化为 &看看是否也是这个原因造成的。您始终可以将其放入调试中,并查看各种寄存器等发生了什么。你尝试过不同的编译器吗?

may sound silly, but, if I were looking at this, I'd perhaps output the nTurn var and see if it were always crashing out on the value. then, perhaps initialize nTurn to that & see if that also causes it. you could always put this into debug and see what is happening with various registers and so forth. did you try different compilers ?

吲‖鸣 2024-10-31 19:27:39

我会使用调试器来捕获错误并查看 nTurn 的值。或者,如果您有崩溃时的核心转储,请将其加载到调试器中以查看崩溃时的 var 值。

还有一点,问题可能出在 nTurn 循环并归零时吗?

I'd use a debugger to catch the fault and see the value of nTurn. Or if you have core dump from the crash load it into the debugger to see the var values at the crash time.

One more point, could the problem be when nTurn wraps round and goes to zero?

·深蓝 2024-10-31 19:27:39

++nTurn 不能直接成为崩溃的根源。您可能存在某种缓冲区溢出,导致 nTurn 变量的内存在不应被指针算术访问的情况下被访问。当与递增结合时,这会导致奇怪的行为。

++nTurn can't be the source of the crash directly. You may have some sort of buffer overflow causing the memory for the nTurn variable to be accessed by pointer arithmetic when it shouldn't be. That would cause weird behavior when combined with the incrementing.

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