0

I'm very new to c++ and programming with pointers. I was trying to pass an argument to a thread, add one to it, and thereafter return a pointer to this result. The main thread should just print the result pointed to by the returned pointer.

#include<stdio.h>
#include<pthread.h>
#include<iostream>

using namespace std;

void* calculator(void* _n) {
    int* n = (int*) _n;
    int* i;
    int result = *n + 1;
    i = &result;

    return i;
}

int main(){
    int input;
    pthread_t calcThread;
    void* exitStatus;
    int* threadResult;

    cout << "Input integer: " << endl;
    cin >> input;
    cout << "Init thread..." << endl;

    pthread_create(&calcThread, NULL, calculator, &input);
    pthread_join(calcThread, &exitStatus);

    // Error around here? 
    threadResult = (int*) exitStatus;
    cout << "Returned: " << *threadResult << endl;
}

The code compiles, but I get a segmentation fault when executing. My guess is that it has something to do with the cast i'm doing, but i can't figure out what.

Any help will be greatly appreciated!

Frederik
  • 23
  • 1
  • 1
  • 3
  • 1
    You return a pointer to an automatic variable (which is located on the stack of that thread). Hence, when the thread function exits, that stack and its content no longer exist. Since you pass in a pointer to an ``int`` from main, simply use ``_n`` to store the result in. – BitTickler Oct 14 '16 at 09:57
  • int result = *n + 1; // <-result is local !!! You must not return the adress of a **local** variable because it will become invalid if the function returns. – Aaron Oct 14 '16 at 09:58

1 Answers1

2
i = &result;

You're returning a pointer to local variable. As soon as it goes out of scope, accessing it yields undefined behavior.

krzaq
  • 16,240
  • 4
  • 46
  • 61