Turning on g++ optimization causes segfault - I don't get it

五迷三道 提交于 2019-12-05 01:40:13

When calculating intensity * color, indirectly this operator is called:

inline Color& Color::operator*= (float f)
{
    r *= f;
    g *= f;
    b *= f;
}

It claims to return a reference to a Color, but doesn't. It should return a reference to *this, like the other operators do:

return *this;

You must realize that it's not the optimization that's breaking your code, the code is already broken. I can't quite see what is going on just by looking at those chunks but seeing as though you are segfaulting on a new statement, I would try and direct my efforts toward checking the input parameters of your new functions. Amongst the many things that happens during an 03 optimization is that the compiler will try to inline function calls, unroll your loops, and create new variables as well as get rid of ones in order to accelerate your execution. As a first step, double check anywhere you have loops and make sure if you're doing something like i < strlen(str) that the statement is not crazy and assert that the input parameters that should not be NULL are in fact not NULL.

Hope this helps.

Time to learn how to debug with gdb!

Recompile all the source code with -g:

find src/ -name "*.cpp" | xargs g++ -I include/ -O3 -g

Then run gdb, load your file, and execute it:

gdb
file a.out
run

gdb will bring you to a command prompt when your program hits the segfault. At the (gdb) prompt type "bt" and hit enter. It will give you the stack trace. The first frame of the stack will be the line of code that caused the segmentation fault.

From there if it's obvious fix it otherwise add the output to your question. Sometimes gdb isn't great at debugging code that's in constructors but try it first and see what it says.

I'm not sure if this is the issue you are seeing, but if you have a class with virtual functions that is used polymorphically, it should have a virtual destructor:

class Light {
   ...
   virtual ~Light {}
   ...
};

Currently, if you would delete the light variable in your main, the ~Light destructor would be called (since the variable has type Light*), instead of the correct ~Point one. Making the destructor virtual fixes this.

There might be some confusion using the member variable pos and the passed in variable pos, try naming them different variable names.

Point(alg::vector pos, Color color, float intensity) : Light(intensity * color), pos(pos) {}

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