我对c++和使用指针进行编程非常陌生。我试图向线程传递一个参数,将一个参数添加到线程中,然后返回指向该结果的指针。主线程应该只打印返回指针指向的结果。
#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;
}代码会编译,但执行时会出现分段错误。我猜这和我所做的演员有关,但我想不出是什么。
任何帮助都将不胜感激!
发布于 2016-10-14 09:56:41
i = &result;返回指向局部变量的指针。一旦超出范围,访问它就会产生未定义的行为。
https://stackoverflow.com/questions/40040206
复制相似问题