Can you help me understand why this code is giving me a segfault as below? Could there be a problem in the way I create threads? I'm having difficulty understanding the issue. Please note that I have simplified the question as much as possible - I am compiling the code with -O3 and getting a zero page error, but the code is valid.
#include <fstream>
#include <sstream>
#include <thread>
#include <iostream>
#include <algorithm>
#include <new>
#include <thread>
#include <string>
class temp {
private:
std::thread m_thread;
std::vector<std::string> m_tokens;
public:
temp()
{
m_thread = std::thread(&temp::run, this);
}
void run()
{
while (1) {
std::string token;
std::cin >> token;
if (std::ranges::find(m_tokens, token) != m_tokens.end()) {
std::cout << "duplicate token" << token << "\n";
continue;
}
m_tokens.push_back(token);
std::cout << token << " added\n";
}
}
};
int main(int argc, char **argv)
{
temp t;
while (1)
;
return EXIT_SUCCESS;
}
ThreadSanitizer:DEADLYSIGNAL
==19246==ERROR: ThreadSanitizer: SEGV on unknown address 0x000000000000 (pc 0x7f81d5f98880 bp 0x7b0800000020 sp 0x7f81d30bf298 T19247)
==19246==The signal is caused by a WRITE memory access.
==19246==Hint: address points to the zero page.
#0 __tsan_func_entry <null> (libtsan.so.0+0x9e880)
#1 std::thread::_State_impl<std::thread::_Invoker<std::tuple<void (temp::*)(), temp*> > >::_M_run() /opt/rh/devtoolset-11/root/usr/include/c++/11/bits/std_thread.h:211 (trading+0x41e3a3)
#2 execute_native_thread_routine <null> (trading+0x437ab3)
#3 start_thread <null> (libpthread.so.0+0x7ea4)
#4 clone <null> (libc.so.6+0xfeb0c)
ThreadSanitizer can not provide additional info.
SUMMARY: ThreadSanitizer: SEGV (/lib64/libtsan.so.0+0x9e880) in __tsan_func_entry
==19246==ABORTING
How is it possible that the code runs without any issues when I run it directly, but gives a segfault error when run as a thread?