c - 多线程程序中的双重释放或损坏

标签 c pthreads free

我遇到了问题

Error in `./thread': double free or corruption (out): 0x00000000021bb030

我的程序的目的是输入:# of thread(argv[1]) 并读取 data.txt 100 个整数并对每个线程进行排序。现在

我的整个代码都在那里..

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *bubble(void *data){

    int * arr = data;   
    int i,j,tmp;
    int size = (sizeof(arr)/4);
    printf("%d",size);

    for(i=0;i<size;i++){
        for(j=0;j<size-1;){
            if(arr[j]>arr[j+1])
            {
                tmp = arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=tmp;
            }

        }

    }

    for(i=0;i<size;i++) printf("%d ",arr[i]);
        printf("\n");
    return ((void *)0);
}

int main(int argc, char **argv){

    FILE * fd;
    int data[100];

    int i,j;
    int tcount = atoi(argv[1]);
    int n = 100/tcount;
    int cursor=0;
    int err;


    pthread_t *thread_t = (pthread_t *)malloc(tcount* sizeof(pthread_t));

    int **data3 = (int **)malloc(tcount *sizeof(int*));
    for( i=0; i<tcount; i++)
        data3[i] = (int *)malloc((100/tcount) *sizeof(int));


    fd = fopen("data.txt", "r");

    printf("tcount = %d n=%d\n",tcount,n);
    for(i =0; i<100;i++)
    {
        fscanf(fd, "%d",&data[i]);
        printf("%d ", data[i]);
    }

    for(j=0;j<tcount;j++){
        for(i=0;i<n;i++){
            data3[j][i]=data[n*j+i];
            printf("%d ",data3[j][i]);
        }
        printf("\n");
    }


    for(i =tcount; i>0;i--)
    {
        err=pthread_create(&thread_t[i],NULL,bubble,(void *)&data3[i]);
            if(err != 0)
                printf("creat thread error");
    }




    for(int i=0; i<tcount; i++)
        free(data3[i]);
    free(data3);
    free(thread_t);
    fclose(fd);

}

最佳答案

您创建线程,然后立即开始释放线程使用的内存,而无需等待它们退出。然后,您还可以在线程退出之前退出进程,从而杀死它们。

您应该等待线程退出,然后再清理并退出程序。您可以通过调用pthread_join来做到这一点:

for(int i=0; i<tcount; i++)
    pthread_join(thread_t[i]);

正如评论中所述 sizeof(arr) 不会给你数组的大小。它将为您提供指针的大小,而不是它所指向的内容。

此外,您的线程创建循环从越界开始,这将导致未定义的行为。最高索引为 tcount - 1,最低索引为 0

最后有一些小注意事项:首先是关于 thread_t 变量的命名。 _t 后缀通常用于类型别名,例如pthread_t。虽然这没有错,但可能会让代码的读者感到困惑。第二个是C中的空指针用NULL表示。不要使用 (void *) 0 (它不可移植)。

关于c - 多线程程序中的双重释放或损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40610969/

相关文章:

c++ - 没有第二个操作数的三元运算符

linux - 线程实现会降低性能

C++:将结构传递给 PThread

c - 将 NULL 分配给指针是否是错误的编程?

c - 为什么 fread() 没有获得预期的字节?

c++ - LLVM IR 是否包含内置函数的代码

c - 关于 pthread_kill() 行为

c - 如何在 C 中释放这个结构?

c - 执行free后进程的内存使用行为

c - 如何 free() 一个结构正确的 malloc()?