Weird C++ bug, program works fine when 2 print statements are added, segfaults without them

十年热恋 提交于 2019-12-24 10:56:44

问题


I am writing some code in C++ that has to compute lots of ray/object intersections and I'm getting a very weird bug that I don't understand.

On some very large instances (lots of triangles and rays) my program segfaults. I've been trying to figure out the source of these segfaults but I've been stumped. I've looked through my code and it doesn't seem like I should ever try to index off the end of an array or access a null pointer. It also doesn't seem like my computer is running out of memory. When I monitor it, it looks like there's still a few hundred megabytes free.

While debugging, I attempted the following: I inserted two print statements in my code in an attempt to determine the exact interesection computation that was causing the segfault. Unfortunately for me, when I inserted the print statements and ran the program again, everything worked. It didn't segfault. So if I remove those two print statements and I run the program it segfaults, and if I keep them in it works fine (although much slower as it has to print everything). Everything else is kept exactly the same, except for the removal/addition of those print statements.

What could possibly cause this to happen? How would adding print statements to a c++ program possibly cause it to not segfault?

If it helps at all, the algorithm is only a single thread and I compiled everything using g++ in Linux.


回答1:


What could possibly cause this to happen? How would adding print statements to a c++ program possibly cause it to not segfault?

Welcome to undefined behaviour.

You need to replace your arrays/pointers/etc with self-checking versions and prove, rather than guesstimate, that you don't have any bugs in these areas.




回答2:


The fact that inserting print statements "fixes" the seg fault is a clear indication that you are accessing memory that you shouldn't.

The best thing to do is to take out the print statements, and run your program through a debugger. Since you are working in Linux, compile your program with a -g flag and run it through gdb. It might tell you exactly in which line it segfaults.



来源:https://stackoverflow.com/questions/10457468/weird-c-bug-program-works-fine-when-2-print-statements-are-added-segfaults-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!