使用-O3在osx上使用g ++优化错误

时间:2011-11-28 00:41:52

标签: c++ macos optimization gcc g++

使用-O3编译时,以下代码生成错误的退出代码。我认为内循环被错误地优化了。使用-O2或-fno-inline它可以工作。制作一个更简单的例子很困难,因为任何小的变化和错误都会消失。

编译:

/usr/bin/g++ -O3 -o bugexample bugexample.cpp

代码:

#include <vector>

int test(std::vector<char>& a, int& b)
{
    std::vector<int> z;
    z.push_back(10);
    z.push_back(10);

    int d = (int)a.size();

    int x = 1;
    for (int j = 0; j < 2; j++)
    {
        int c = j - 1;

        for (int i = 0; i < d; i++) 
        {
            if (j == 0)
            {
            }
            else if (i == 0)
            {
            }
            else
            {
                if (a[j] == a[i - 1])
                {
                    b = c + 1;
                    x = 2;
                }
                z[i] = 1;
            }
        }
    }

    return x;
}


int main(int argc, char* argv[])
{
    std::vector<char> a;
    a.push_back('a');
    a.push_back('a');
    int b = 1;
    return test(a,b);
}

编译器版本:

/usr/bin/g++ -v
Using built-in specs.
Target: i686-apple-darwin10
Configured with: /var/tmp/gcc/gcc-5666.3~123/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5666) (dot 3)

对任何问题感兴趣,或证明我的错。

编辑:产生的退出代码是1,而它应该是b 2。

1 个答案:

答案 0 :(得分:1)

嗯这是某种混淆代码竞赛吗?

据我所知,你试图对输入矢量进行某种回文测试。只有,

  • 循环var j的硬编码上限为2(也应该是a.size()?)
  • 您只返回最后一个位置的支票
  • 你有各种多余的条件
  • 你有无偿的非常规论点
  • 您有未使用的z向量
  • 你对bool不必要地使用int(1 =&gt; false - not found,2 =&gt; true - found)
  • 您不必使用out参数b;我将bool返回类型替换为b的值(b == - 1表示找不到匹配项)

当简化这些东西的代码时,我得到了这个代码,并且(就像你自己的代码一样)它在g ++ 4.6.1上的所有优化级别都表现相同:

#include <vector>

int test(const std::vector<char>& a)
{
    /* int j = 1; // was: for (int j = 1; j < 2; j++) */

    for (int i = a.size()-1; i > 1; i--) 
        if (a[1] == a[i - 1])
            return 1;

    return -1;
}


int main(int argc, char* argv[])
{
    std::vector<char> a(2, 'a');
    int b = test(a);

    return b==-1? 1 : 2;
}
相关问题