C++线程中的分段错误

Chr*_*ris 3 c++ pthreads segmentation-fault

我正在尝试在C++中设置一个基本的线程类,但是当我尝试创建一个线程时,我遇到了一个seg错误.以下是GDB报告的内容:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000401b68 in StartThread (pFunction=
    0x401ad2 <FindPrimesThread(void*)>, pLimit=5000000) at Thread.cpp:35
35          state->mLimit = pLimit;
Run Code Online (Sandbox Code Playgroud)

当我试着像这样打电话:

ThreadState *primesState = StartThread(FindPrimesThread, 5000000);
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

Thread.hpp

#ifndef THREAD_HPP
#define THREAD_HPP

#include <pthread.h>
#include "Types.hpp"

typedef struct {
    ulong       mLimit;     // Upper limit of numbers to test 
    int         mStarted;   // True if the thread started successfully
    int         mExitCode;  // Thread exit code
    pthread_t   mThreadId;  // Thread ID
} ThreadState;

// Defines a type named ThreadFunction which is a pointer to a function with void * as the parameter and
// void * as the return value.
typedef void *(*ThreadFunction)(void *);

ThreadState *StartThread
    (
    ThreadFunction const pFunction,  // Pointer to the thread function
    ulong const          pLimit      // Upper limit of numbers to test
    );

#endif
Run Code Online (Sandbox Code Playgroud)

Thread.cpp

#include "Amicable.hpp"
#include "Keith.hpp"
#include "Main.hpp"
#include "Prime.hpp"
#include "Thread.hpp"

ThreadState *StartThread
    (
    ThreadFunction const pFunction,  // Pointer to the thread function
    ulong const          pLimit      // Upper limit of numbers to test
    ) {
        ThreadState *state;
        state->mLimit = pLimit;
        pthread_t threadId;
        state->mStarted = pthread_create(&threadId, NULL, pFunction, (void *)state);
        if(state->mStarted == 0){
            state->mThreadId = threadId;
        }
        return state;
    }
Run Code Online (Sandbox Code Playgroud)

对这里出了什么问题有什么想法吗?

TJD*_*TJD 7

ThreadState *state;
state->mLimit = pLimit;
Run Code Online (Sandbox Code Playgroud)

您正在写入尚未分配的内存

  • +1确实.在前往任何*靠近*线程之前必须先理解指针. (3认同)