Crash on exit while multi-threading

Hi all. I'm new to C++ and I've run into a problem I can't solve, so I was wondering if I could get some help. I was writing a program and it started crashing on exit (segment fault), after the 'return 0' in main(). I figure it's an std destructor but beyond that I have no idea.

Forgive the odd state of the code below. I started with the program I was writing and just stripped out as much as I could, while making sure the crash persisted. If I remove any of the remaining code the crash disappears, even the seemly unrelated or scoped code. The problem is that I don't know what is causing it. Can anyone spot an error?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <fstream>
#include <condition_variable>
#include <mutex>
#include <thread>

/* Call stack results:
#0 6FC8407F	libstdc++-6!_ZNSo5flushEv() (C:\Program Files\mingw-builds\x64-4.8.1-posix-seh-rev5\mingw64\bin\libstdc++-6.dll:??)
#1 FFFFFFFF	msvcrt!_iob() (C:\Windows\system32\msvcrt.dll:??)
#2 6FCCAF40	libstdc++-6!_ZSt3cin() (C:\Program Files\mingw-builds\x64-4.8.1-posix-seh-rev5\mingw64\bin\libstdc++-6.dll:??)
#3 00335388	?? () (??:??)
#4 ??	?? () (??:??)
*/

bool running = false;
std::thread* threadlist = 0;
std::mutex m;
std::condition_variable cv;

void threadfunc()
{
    std::unique_lock<std::mutex> lk(m);
    while (running) cv.wait(lk);
}

int main()
{

    std::unique_lock<std::mutex> lk2(m, std::defer_lock);

    std::ofstream logfile("log.txt");
    std::clog.rdbuf(logfile.rdbuf());

    running = true;
    threadlist = new std::thread(&threadfunc);

    int t = 1;
    {
        std::lock_guard<std::mutex> macro_lk(m);
        std::cout << t << std::endl;
    }
    {
        std::lock_guard<std::mutex> macro_lk(m);
    }

    running = false;
    cv.notify_all();
    threadlist->join();
    delete threadlist;
    threadlist = 0;

    return 0;
}
You set std::clog to use the stream buffer of logfile but logfile will be destructed before std::clog so std::clog ends up with a stream buffer pointer that is no longer valid. Calling std::clog.rdbuf(nullptr); before main() ends fixes the problem.
I would never have figured that out, well, maybe in a few weeks. I thought it was something to do with the mutex or conditional. Thank you so much Peter.
Topic archived. No new replies allowed.