简体   繁体   中英

thread_local vector segmentation fault at end of program in C++

I'm trying to make a multi-threaded program but am having a weird problem with thread local vectors. Here's the (stripped-down to only have the error) code:

#include <vector>
#include <iostream>
thread_local std::vector<int> vec;
int main(){
    vec.push_back(3);
    std::cout << vec[0];
    // Make you push enter to show the error is at the end
    std::cin.ignore();
}

The program compiles fine and runs mostly fine, but after I press enter I get a "program has stopped working" message. I ran it in gdb and got this error:

Program received signal SIGSEGV, Segmentation fault.
0x004030b0 in std::vector<int, std::allocator<int> >::~vector() ()

Somehow, there's an error in the vector's destructor. Going through it with a breakpoint shows that this error happens as the program is quitting.

Making the vector not thread local makes the program work, but of course I need it to be thread local. If I don't interact with the vector at all, the program works fine.

I'm thinking I'll have to use some alternative, but does anybody know a way to make this work? Thanks!

EDIT: I'm stupid and forgot more info on my system. I'm using Windows Vista 64-bit. Running g++ -v gives me:

Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=C:/MinGW/bin/../libexec/gcc/i686-w64-mingw32/5.2.0/lto-wrapper.exe
Target: i686-w64-mingw32
Configured with [edited out because it's too big and probably not relevant]
Thread model: posix
gcc version 5.2.0 (i686-posix-dwarf-rev0, Built by MinGW-W64 project)

The thread model might actually have a lot to do with it.

It is setup dependent; I have successfully compiled and run your example program on Windows 7 (64 bit) with the 64 bit MinGW. Perhaps it is related to the fact that you use the 32 bit MinGW installation on 64 bit platform? My g++ -v gives the following (same version and thread model as yours, different arch):

Using built-in specs.
COLLECT_GCC=g++
Target: x86_64-w64-mingw32
Thread model: posix
gcc version 5.2.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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