4

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

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

当我尝试这样称呼它时:

ThreadState *primesState = StartThread(FindPrimesThread, 5000000);

这是我的代码:

线程.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

线程.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;
    }

知道这里出了什么问题吗?

4

2 回答 2

7
ThreadState *state;
state->mLimit = pLimit;

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

于 2012-05-01T04:22:00.083 回答
3

您在 ThreadState 中有一个未初始化的指针。在第 35 行,您创建了一个指向 ThreadState 的指针,但您从未将该指针指定为指向任何 ThreadState 对象。

请记住,指针只是一个内存地址。“ThreadState*”只是意味着,“这是一个内存地址,我们可以将内存中我持有的地址处的数据解释为一个ThreadState对象。”

也许您打算执行“ThreadState *state = new ThreadState();”?不要忘记,有人在使用完 ThreadState 对象后需要去删除它,以免内存泄漏!

于 2012-05-01T04:24:35.437 回答