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