简体   繁体   English

为什么g ++优化了以下代码的关键部分?

[英]Why does g++ optimize out a critical section of the following code?

The following code causes a crash in my program, because 以下代码导致程序崩溃,因为

void fractalizeSegment() {
        // Assume next != NULL
        double deltaX = next->x - x;
        double deltaY = next->y - y;

        // Add 3 new points labeled a1, a2, a3 from this to next
        Point a3(x + 2.0*deltaX/3.0, y + 2.0*deltaY/3.0, next);
        double sqr3 = std::sqrt(3.0);
        Point a2(x + deltaX/2.0 - sqr3*deltaY/2.0,
             y + deltaY/2.0 + sqr3*deltaX/2.0,
             &a3);
        Point a1(x + deltaX/3.0, y + deltaY/3.0, &a2);

        next = &a1;
    }

Is somehow optimized to 以某种方式优化

void fractalizeSegment() {
    next = &a1;
}

The method is called on p0 = {x = 0, y = 0, next = 0x7fffffffe100}, which point to p1 = {x = 1, y = 0, next = 0x0}. 在p0 = {x = 0,y = 0,next = 0x7fffffffe100}上调用该方法,其指向p1 = {x = 1,y = 0,next = 0x0}。

By analyzing the program in the debugger I found that when I'm in the method fractalizeSegment: 通过分析调试器中的程序,我发现当我在方法fractalizeSegment时:

a1 = {x = 6.9533558075099091e-310, y = 6.9533558075098597e-310, next = 0x7fffffffe190}

In address a1.next there is 在地址a1.next中有

a2 = {x = 6.9533558074508189e-310, y = 4.9406564584124654e-324, next = 0x34}.

Trying to deference (*a2.next).next causes a segmentation fault. 试图遵循(* a2.next).next会导致分段错误。

Why does g++ optimize my code like this? 为什么g ++会像这样优化我的代码? How can I prevent it? 我该怎样预防呢?

The current workaround I found was printing out the values of a1, a2, and a3, this prevented the optimization. 我发现当前的解决方法是打印出a1,a2和a3的值,这阻止了优化。

a1 is a local automatic variable that will be destroyed upon returning from the function, so any use of *next after that will be undefined. a1是一个本地自动变量,在从函数返回时将被销毁,因此在此之后使用*next将是未定义的。 The compiler thinks that surely you will not use those values so why bother computing them. 编译器认为你肯定不会使用这些值,所以为什么要费心计算它们。

You probably want to create a1 in the heap: 您可能想在堆中创建a1

next = new Point(x + deltaX/3.0, y + deltaY/3.0, &a2); //no need of a1.

Maybe also a2 and a3 should be dynamically allocated, but that depends on the implementation of Point , that you did not show. 也许也应该动态分配a2a3 ,但这取决于你没有展示的Point的实现。

And remember to delete the allocated objects somewhere. 并记得在某处delete已分配的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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