[英]*** glibc detected *** free(): invalid pointer
我有以下代码会生成*** glibc detected *** free(): invalid pointer
的*** glibc detected *** free(): invalid pointer
每当我运行代码时,都会发生*** 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));
}
当前,您的线程任务在线程堆栈上返回一些值。 当线程完成时,不能保证* temp指向有效的东西。
因此在这个电话之后
pthread_join(threads[j], (void**)(&temp));
temp指向线程中sum的旧位置,但是如果线程结束,它将不再存在。 使用它会导致不确定的行为。
后来,您释放了temp,该温度指向另一个堆栈上的双精度型,但由于堆栈分配超出范围,堆栈分配是自动释放的,因此请注意不要释放。
free(temp);
您可能想做的是:
void* task(void *data) {
double* sum = new double;
*sum = 5;
pthread_exit(static_cast<void*>(sum) );
}
然后在主线程加入线程之后
delete temp;
在您的代码中声明:
double *temp;
您永远不会将malloc分配给该地址,而是稍后将其释放。 这将产生错误。 删除free(temp),它应该可以工作。 实际上,尽管您通过取消引用* temp而没有存储引入了新的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.