Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault in C++ thread

I'm trying to set up a basic threaded class in C++, but I'm getting a seg fault when I try to create a thread. Here's what GDB reports:

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

when I try to call it like this:

ThreadState *primesState = StartThread(FindPrimesThread, 5000000);

Here's my code:

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

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;
    }

Any idea on what's going wrong here?

like image 654
Chris Avatar asked Dec 27 '22 01:12

Chris


2 Answers

ThreadState *state;
state->mLimit = pLimit;

You are writing to memory you haven't allocated

like image 115
TJD Avatar answered Jan 05 '23 14:01

TJD


You have an uninitialized pointer in ThreadState. On line 35, you create a pointer to a ThreadState, but you never assign that pointer to point to any ThreadState object.

Remember, a pointer is just a memory address. "ThreadState*" just means, "this is a memory address, and we can interpret the data in memory at the address I hold to be a ThreadState object."

Perhaps you meant to do "ThreadState *state = new ThreadState();"? Don't forget, someone will need to go and delete that ThreadState object when they're done using it so as not to leak memory!

like image 32
int3h Avatar answered Jan 05 '23 14:01

int3h