C 中损坏的大小与 prev_size

Has*_*mad 1 c pthreads dynamic-memory-allocation

每当我在线程中分配动态内存时,都会出现“大小损坏与 prev_size”错误。每当我在 main() 中分配内存时,它都可以正常工作。但是在线程中分配动态内存会产生错误。

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

void *fib(void *p);
struct mystruct
{
    int *array;
    int size;
};

int main(int argc, char *argv[])
{
    pthread_t tid;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    struct mystruct obj;

    obj.size = atoi(argv[1]);;

    pthread_create(&tid, &attr, fib, (void *)&obj);
    pthread_join(tid, NULL);
}

void *fib (void *p)
{
    struct mystruct *x = (struct mystruct *)p;
    x->array = (int *) malloc (x->size);

    for (int i=0; i<x->size; i++){
        x->array[i] = i;
        printf("The array is = %d\n", x->array[i]);
    }   
}
Run Code Online (Sandbox Code Playgroud)

我已添加快照以获取详细信息。

错误说大小损坏 vs prev_size

谢谢!

Dav*_*aro 5

尝试使用以下行:

x->array =  malloc (x->size*sizeof(int));
Run Code Online (Sandbox Code Playgroud)

您需要为x->size整数分配空间。malloc接受您需要的字节数作为参数。对于n int您需要n的大小(以字节为单位)的倍数int

不要忘记return从主要。