Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mystifying UB/segfault only on gcc - is the code ill-formed? [duplicate]

Tags:

c++

gcc

lambda

I have the following SSCCE:

#include <iostream>
#include <string>

void foo(const std::string &a) {
  std::cout << a << std::endl;
}

template <typename... Args>
void bar(Args &&... args) {
  [&]() {
    [&]() {
          foo(args...);
      }();
  }();
}

int main() {
 const std::string x("Hello World!");
 bar(x);
}

Under clang++ (3.9.1) this compiles and emits "Hello World". Gcc 6.3 fails with a segmentation fault under -O3.

I can fix the problem by explicitly passing the pointer and the pack by reference, replacing [&]() with [&args...](). However, up to now, I thought that [&] would do the same as listing all arguments one by one.

So what is going wrong here?

P.S: This is not limited to -O3. -O0 does not segfault but does not return the expected result ("Hello World!"):

[:~/tmp] $ g++-6 -std=c++1z param.cpp && ./a.out

[:~/tmp] $

P.P.S: Further reduced SSCCE. Now I don't even get a diagnostic with -Wall -Wextra anymore.

like image 843
mrks Avatar asked Jan 20 '17 18:01

mrks


People also ask

Why does segfault occur?

A segmentation fault (aka segfault) is a common condition that causes programs to crash; they are often associated with a file named core . Segfaults are caused by a program trying to read or write an illegal memory location.

Is segmentation fault a runtime error?

The segmentation error is one of the runtime error, that is caused because of the memory access violation, like accessing invalid array index, pointing some restricted address etc.


1 Answers

I strongly suspect a g++ bug.


Here are some notes:

  • replacing std::string with any elementary type, e.g., int still does not work
  • clang and VC++ will work just as intended
  • not passing parameter pack by reference causes an internal compiler error with g++ 7.0.1 with the following output:

internal compiler error: in make_decl_rtl, at varasm.c:1304

...

Please submit a full bug report, with preprocessed source if appropriate.

Please include the complete backtrace with any bug report. See http://gcc.gnu.org/bugs.html for instructions.

like image 167
AMA Avatar answered Sep 20 '22 09:09

AMA