0

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

2 回答 2

1

当前,您的线程任务在线程堆栈上返回一些值。当线程完成时,不能保证 *temp 将指向有效的东西。

因此,在这个电话之后

pthread_join(threads[j], (void**)(&temp));

temp 指向线程中 sum 的旧位置,但如果线程完成,它不再存在。使用它会导致未定义的行为。

但后来你释放了指向另一个堆栈上的双精度的 temp ,但需要注意的是 free 因为堆栈分配在超出范围时会自动释放。

free(temp);

你可能想做的是:

void* task(void *data) {
    double* sum = new double;
    *sum = 5;
    pthread_exit(static_cast<void*>(sum) );
}

然后在加入线程后在 main

delete temp;
于 2013-07-31T20:47:29.930 回答
0

在您的代码中,您声明:

double  *temp;

您永远不会 malloc 到该地址,但后来您将其释放。这将产生错误。删除免费(临时),它应该可以工作。实际上,尽管您通过取消引用 *temp 而不进行存储引入了新错误。

于 2013-07-31T20:40:10.923 回答