【发布时间】:2013-08-01 12:48:31
【问题描述】:
我有以下代码,每当我运行代码时都会产生*** 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));
}
【问题讨论】:
-
不相关,但您正在传回对 sum 的引用,但 sum 在堆栈上。将它添加到 main 中的 sum 变量时,此变量可能不存在。
-
@MWB 这不是
pthread_join()的重点吗?它阻塞父线程,直到任务完成。这让我相信sum应该存在并且它的值应该存储在temp -
来自手册页 (man7.org/linux/man-pages/man3/pthread_exit.3.html) retval 指向的值不应位于调用线程的堆栈中,因为该堆栈的内容在线程终止后未定义。
-
@MWB 我明白你的意思了。感谢您指出这一点。
-
@AlexBrooks 您在编辑后没有为
new分配内存。
标签: c++ pointers pthreads free glibc