*** glibc detected *** free(): invalid pointer
我有以下代码,每当我运行代码时都会产生错误。
main.h
:
#ifndef PTHREAD_CALC_H_
#define PTHREAD_CALC_H_
void* task(void*);
#endif
main.cxx
:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>
#include "main.h"
int main(int argc, char* argv[]) {
pthread_t *threads = (pthread_t*)malloc(sizeof(pthread_t)*2);
double *temp;
double sum = 0.0;
for (int j = 0; j < 2; j++) {
pthread_create(&(threads[j]), NULL, task, NULL);
}
for (int j = 0; j < 2; j++) {
pthread_join(threads[j], (void**)(&temp));
sum += *temp;
}
free(threads);
free(temp);
return 0;
}
void* task(void *data) {
double sum = 5;
pthread_exit((void*)&sum);
return NULL;
}
我很难确定导致错误的原因。非常感谢任何帮助。如果我能提供任何其他帮助查明问题,请告诉我。
谢谢
编辑
为了完成,这里是按预期执行的结果代码:
main.cxx
:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>
#include "main.h"
int main(int argc, char* argv[]) {
pthread_t *threads = (pthread_t*)malloc(sizeof(pthread_t)*2);
double *temp;
double sum = 0.0;
for (int j = 0; j < 2; j++) {
pthread_create(&(threads[j]), NULL, task, NULL);
}
for (int j = 0; j < 2; j++) {
pthread_join(threads[j], (void**)&temp);
sum += temp;
delete temp;
}
free(threads);
return 0;
}
void* task(void *data) {
double* sum = new double;
*sum = 5.0;
pthread_exit(static_cast<void*>(sum));
}