草庐IT

c++ - 程序员的错误或 gcc-5.1.0 的错误?

coder 2024-02-13 原文

我尝试使用带有优化标志 -O1/-O2/-O3/-Og 的 gcc-5.1.0 编译一个大型软件。它给了我警告 -Wmaybe-uninitialized-Wuninitialized 并在运行时失败。调试后我找到了导致它的代码,但我无法理解为什么。我减少了重现失败的代码:

#include <cstdlib>
#include <iostream>

template<class T>
struct foo {
    template<class U>
    char bar(const U &x) {
        //return id(x)[0];
        const T &y = id(x);
        return y[0];
    }

    const T &id(const T &elem) {
        return elem;
    }
};

int main(void) {
    foo<const char *> f;
    char *str = "hello world";
    //std::cout << f.bar((const char *)str) << std::endl;
    std::cout << f.bar(str) << std::endl;
    return 0;
}

gcc-5.1.0 给出以下警告:

g++ -Og -Wall -Wextra -Wno-write-strings    test.cpp   -o test
test.cpp: In function ‘int main()’:
test.cpp:10:19: warning: ‘<anonymous>’ is used uninitialized in this function [-Wuninitialized]
         return y[0];
                   ^
test.cpp:9:24: note: ‘<anonymous>’ was declared here
         const T &y = id(x);
                        ^

程序在运行时收到 SIGSEGV 并崩溃。由于优化很难调试,但在玩过代码后我认为问题是 const T &y = id(x);NULL 分配给 y。 (通过将 return y[0]; 替换为仅返回 y[0] 的函数调用来解决这个问题。)我目前无法使用其他版本测试代码gcc,但是当使用 gcc-4.9.2 编译时,派生示例的代码可以正常工作。当与 clang-3.6.1 一起编译时,它也可以在任何优化级别下正常工作。 我的下一步是试图找出导致它的确切优化是什么,所以我将我能够找到的所有 gcc 优化标志放入我的 makefile 中,但它在没有警告的情况下编译并且在运行时不会崩溃。

我的问题是:

  • 它是正确的 C++ 代码吗?
  • 它是 gcc-5.1.0 中的已知/未知错误吗?
  • 在上面的例子中,我理解正确吗 T = [const char *]; U = [char *] 并且当我编写 const T &y = id(x); 时,应该从 char * 隐式转换 x const char *y 是对 const char *?
  • 的常量引用
  • 如果模板有误,具体错误是什么?
  • 如何找出导致它的确切优化标志是什么?

注意:取消注释任何注释行可以修复程序。

$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-unknown-linux-gnu/5.1.0/lto-wrapper
Target: x86_64-unknown-linux-gnu
Configured with: /build/gcc-multilib/src/gcc-5-20150623/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-shared --enable-threads=posix --enable-libmpx --with-system-zlib --with-isl --enable-__cxa_atexit --disable-libunwind-exceptions --enable-clocale=gnu --disable-libstdcxx-pch --disable-libssp --enable-gnu-unique-object --enable-linker-build-id --enable-lto --enable-plugin --enable-install-libiberty --with-linker-hash-style=gnu --enable-gnu-indirect-function --enable-multilib --disable-werror --enable-checking=release --with-default-libstdcxx-abi=c++98
Thread model: posix
gcc version 5.1.0 (GCC)

我试过的 gcc 优化标志:

-falign-functions -falign-jumps -falign-labels -falign-loops -fassociative-math
-fauto-inc-dec -fbranch-count-reg -fbranch-probabilities -fbranch-target-load-optimize
-fbranch-target-load-optimize2 -fbtr-bb-exclusive -fcaller-saves -fcheck-data-deps -fcheck-new
-fcombine-stack-adjustments -fcompare-elim -fconserve-stack -fcprop-registers -fcrossjumping
-fcse-follow-jumps -fcse-skip-blocks -fcx-fortran-rules -fcx-limited-range -fdata-sections
-fdce -fdefer-pop -fdelete-null-pointer-checks -fdevirtualize -fdevirtualize-speculatively
-fdse -fearly-inlining -fexpensive-optimizations -fext-numeric-literals -ffast-math
-ffinite-math-only -ffloat-store -ffor-scope -fforward-propagate -ffriend-injection
-ffunction-sections -fgcse -fgcse-after-reload -fgcse-las -fgcse-lm -fgcse-sm -fguess-branch-probability
-fhoist-adjacent-loads -fif-conversion -fif-conversion2 -findirect-inlining -finline-functions
-finline-functions-called-once -finline-small-functions -fipa-cp -fipa-cp-alignment -fipa-cp-clone
-fipa-icf -fipa-matrix-reorg -fipa-profile -fipa-pta -fipa-pure-const -fipa-ra -fipa-reference
-fipa-sra -fipa-struct-reorg -fisolate-erroneous-paths-dereference -fivopts -fkeep-inline-functions
-fkeep-static-consts -floop-block -floop-interchange -floop-strip-mine -flra-remat -fmerge-all-constants
-fmerge-constants -fmodulo-sched -fmodulo-sched-allow-regmoves -fmove-loop-invariants -fms-extensions
-fnothrow-opt -fomit-frame-pointer -foptimize-register-move -foptimize-sibling-calls -foptimize-strlen
-fpartial-inlining -fpeel-loops -fpeephole2 -fpermissive -fpredictive-commoning -fprefetch-loop-arrays
-fprofile-correction -fprofile-generate -fprofile-use -fprofile-values -freciprocal-math -fregmove
-frename-registers -freorder-blocks -freorder-blocks-and-partition -freorder-functions -frerun-cse-after-loop
-freschedule-modulo-scheduled-loops -frounding-math -fsched-interblock -fsched-spec -fsched-spec-load
-fsched-spec-load-dangerous -fsched-stalled-insns -fsched-stalled-insns-dep -fsched2-use-superblocks
-fsched2-use-traces -fschedule-insns -fschedule-insns2 -fsee -fsel-sched-pipelining
-fsel-sched-pipelining-outer-loops -fselective-scheduling -fselective-scheduling2 -fshrink-wrap
-fsignaling-nans -fsingle-precision-constant -fsized-deallocation -fsplit-ivs-in-unroller
-fsplit-wide-types -fssa-phiopt -fstack-protector -fstack-protector-all -fstrict-aliasing
-fstrict-overflow -fthread-jumps -ftracer -ftree-bit-ccp -ftree-builtin-call-dce -ftree-ccp
-ftree-ch -ftree-coalesce-vars -ftree-copy-prop -ftree-copyrename -ftree-dce -ftree-dominator-opts
-ftree-dse -ftree-forwprop -ftree-fre -ftree-loop-distribute-patterns -ftree-loop-distribution
-ftree-loop-im -ftree-loop-ivcanon -ftree-loop-linear -ftree-loop-optimize -ftree-loop-vectorize
-ftree-partial-pre -ftree-phiprop -ftree-pre -ftree-pta -ftree-reassoc -ftree-sink -ftree-slp-vectorize
-ftree-slsr -ftree-sra -ftree-switch-conversion -ftree-tail-merge -ftree-ter -ftree-vect-loop-version
-ftree-vectorize -ftree-vrp -funit-at-a-time -funroll-all-loops -funroll-loops -funsafe-loop-optimizations
-funsafe-math-optimizations -funswitch-loops -fuse-cxa-atexit -fvariable-expansion-in-unroller
-fvect-cost-model -fvisibility-inlines-hidden -fvisibility-ms-compat -fvpt -fvtv-counts -fvtv-debug
-fweb -fwhole-program

最佳答案

您的字符串文字(非法)绑定(bind)到 char*:

char *str = "hello world";

这是 C 的遗留转换,自 C++98(或 C++03?)以来已被弃用,并在 C++11 中被删除。 gcc 仍然允许它作为扩展,clang++ 也是如此。

当你调用f.bar(str)时,它推导出U == char*,所以它的函数参数类型变成了char* const&.

using U = char*;
template<>
char bar(const U &x) { // char* const& x
    const T &y = id(x);
    return y[0];
}

但是,您已经使用模板参数 char const* 实例化了 f,因此 id 的函数参数类型是 char const* 常量&:

const T &id(const T &elem) { // char const* const& elem
    return elem;
}

因此,bar 中的表达式 id(x) 必须从 char* 转换为 char const*,这会创建一个临时文件。这个临时值一直持续到完整表达式 const T& y = id(x); 结束,因此创建了一个悬空引用 y


基本上,您的假设之​​一是不正确/不完整的:

Do I understand it correctly that in the example above T = [const char*]; U = [char *] and when I write const T &y = id(x); there should be implicit convertion of x from char * to const char * and y is a constant reference to const char *?

类型T const*T* 不是引用兼容的。有关详细信息,请参阅 [dcl.init.ref]。但是,T* 可以转换为 T const*,因此会创建一个临时变量并绑定(bind)到 T const*&。这类似于:

int i = 42;
double const& d = i; // creates a temporary double and binds it to d

这是所有引用不兼容类型的行为,其中源可以隐式转换为目标类型(具有转换函数/运算符的类类型除外)。

为什么 T const*T* 引用不兼容?同样的推理适用于 T const**T**,它们也是不兼容的。这可以防止出现细微错误,请参阅 https://stackoverflow.com/a/2908332/

关于c++ - 程序员的错误或 gcc-5.1.0 的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31517791/

有关c++ - 程序员的错误或 gcc-5.1.0 的错误?的更多相关文章

  1. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  2. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  3. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  4. ruby - 在 Ruby 中编写命令行实用程序 - 2

    我想用ruby​​编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序

  5. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  6. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  7. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  8. ruby-on-rails - Rails 应用程序中的 Rails : How are you using application_controller. rb 是新手吗? - 2

    刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr

  9. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  10. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

随机推荐