0

I have the following simple code:

// test.hpp

#pragma once

#include <deque>

struct A {
    static thread_local std::deque<int> g;
};
// test.cpp

#include "test.hpp"

thread_local std::deque<int> A::g = std::deque<int>();
// main.cpp

#include "test.hpp"

int main() {
    A::g.emplace_back(0);
    return 0;
}

When I compile it with Clang, it finished with code 0 and everything is OK. However, if I compile it with GCC, it crashes with SIGSEGV.

A bit of debugging into the GCC STL source code showed me that during emplace_back, the internal pointers of the std::deque seem to be NULL, which causes the failure on an attempt to allocate memory and place the int into it.

Am I doing something wrong, or is this a GCC bug?

Versions:

  • Clang (which produces a working binary): Homebrew clang version 16.0.2
  • GCC (which produces a crashing binary): g++-13 (Homebrew GCC 13.1.0) 13.1.0
  • OS: macOS Monterey 12.5.1

P.S. Replacing the std::deque with std::vector somehow fixes the problem (GCC-produces binary finishes with code 0)

UPD:

clang compilation:

clang++ -std=c++20 main.cpp test.cpp -o run

gcc compilation (both produced executables fail):

g++-13 -std=c++20 main.cpp test.cpp -o run

or

g++-13 -std=c++20 -pthread -c test.cpp main.cpp && g++-13 -pthread test.o main.o -o run

The failure message I am getting:

[1]    95879 segmentation fault  ./run
  • If you Google "gcc static thread_local crash" you will find a lot of similar questions on SO. Try to make `g` a global variable in .cpp. – 273K May 04 '23 at 15:49
  • 1
    What is the crash _stack trace_ ? What is the _actual_ compile line? Does the crash go away if you use `-pthread` at compile and link time? – Employed Russian May 05 '23 at 02:42
  • @273K Yeah, I have seen those and indeed your proposed solution works, but I was wondering why my code fails though it seems fine – tigrkoshka May 05 '23 at 23:56
  • @EmployedRussian I have edited the question to add the compile commands and the error message, please see above, the `-pthread` flag did not help:( – tigrkoshka May 05 '23 at 23:57
  • `-pthread` is not needed in new GCC anymore. – 273K May 06 '23 at 00:01
  • I have also seen a similar question https://stackoverflow.com/questions/45719784/thread-local-static-member-template-definition-initialisation-fails-with-gcc, but there the author says that removing a template parameter (which I do not have here) fixes the problem. The author went on and submitted a bug report for gcc-8 which still does not seem to be fixed, so it may be a similar issue – tigrkoshka May 06 '23 at 00:04

0 Answers0