Search code examples
c++multithreadingsdl

Create SDL_thread with string parameter


I am trying to make a multithreading program with a string as the input. Using SDL_CreateThread, I attempted to build a simple implementation like so:

#include <stdio.h>
#include <string>
#include <SDL_thread.h>

int threadFunction(void* data) {
    std::string* parameter = static_cast<std::string *>(data);
    printf("Thread data: %s\n", parameter);
    return 0;
}

int main(int argc, char const *argv[]) {
    SDL_Thread* threadID = SDL_CreateThread(threadFunction, "test", (void*)"Enter string here");
    SDL_DetachThread(threadID);
    return 0;
}

It works perfectly fine but whenever I put an integer into the string (such as "123", not directly the number 123) and then attempt to parse the integer in the thread, I get a Segmentation Fault: 11. My attempt is int i = std::stoi(parameter->c_str());

Can anyone explain why? Does it have to do with casting from void*?


Solution

  • Alright, you first pass a pointer to array of char (void*)"Enter string here" as thread parameter then you cast this pointer to a pointer to string static_cast<std::string *>(data). ::std::string is a class and under no condition it is acceptable to performs such cast. Also you implicitly cast a pointer to string to a pointer to array of chars when printf("Thread data: %s\n", parameter) but that does not detonate an error because it does point to array of char, not at string.

    int threadFunction(void* data) {
    const char * parameter = static_cast< const char * >(data); // correct cast