简体   繁体   中英

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM