Compiler optimization makes program crash

时光怂恿深爱的人放手 提交于 2019-12-03 15:57:29

There are a few classes of bugs that commonly arise in optimized builds, that often don't arise in debug builds.

  1. Un-initialized variables. The compiler can catch some but not all. Look at all your constructors, look at global variables. etc. Particularly look for uninitialized pointers. In a debug build memory is reset to zero, but in a release build it isn't.

  2. Use of temporaries that have gone out of scope. For example when you return a reference to a local temporary in a function. These often work in debug builds because the stack is padded out more. The temporaries tend to survive on the stack a little longer.

  3. array overruns writing of temporaries. For example if you create an array as a temporary in a function and then write one element beyond the end. Again, the stack will have extra space in debug ( for debugging information ) and your overrun won't hit program data.

There are optimizations you can disable from the optimized build to help make debugging the optimized version easier.

-g -O1 -fno-inline -fno-loop-optimize -fno-if-conversion -fno-if-conversion2 \
  -fno-delayed-branch

This should make stepping through your code in the debugger a little easier to follow.

Another suggestion is that if the assertions you have do not give you enough information about what is causing the problem, you should consider adding more assertions. If you are afraid of performance issues, or assertion clutter, you can wrap them in a macro. This allows you to distinguish the debugging assertions from the ones you originally added, so they can be disabled or removed from your code later.

1) Use valgrind on the broken version. (For that matter, try valgrind on the working version, maybe you'll get lucky.)

2) Build the system with "-O1 -g" and step through your program with gdb. At the crash, what variable has an incorrect value? Re-run your program and note when that variable is written to (or when it isn't and should have been.)

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