为什么我会出现内存泄漏(此初始化导致的分段错误)?

Why am I getting memory leaks (segmentation faults from this initialization)?

struct node {
    void *info;
    struct node *nextNode;
}

struct linked {
    struct node* Head;
    struct node* Tail;
}

struct linked* pro[32]

void initialize_list()
     printf("seg 1\n");
     for (int i = 0; i < 32; i++) {
        if(!(pro[i] = (struct linked *) malloc(sizeof(struct linked)))) {
        pro[i]->Head = pro[i]->Tail = NULL;
        }
     }
     printf("seg 2\n");
}

我不知道为什么,但是当我在 main

中调用 initialize_list() 函数时
int main() {
    initialize_list();
}

我有时会得到输出:

seg 1 
segmentation fault

有时

seg 1 
seg 2

有时我的意思是,当我 运行 程序运行 8 次时,它可能 运行 在 6 运行 秒和 2 秒内输出正确运行s 它可能会产生分段错误输出。 你能帮我弄清楚这个初始化有什么问题吗?我想为什么会造成一些内存泄漏?

if(!(pro[i] = (struct linked *) malloc(sizeof(struct linked)))) {

应该是

if((pro[i] = (struct linked *) malloc(sizeof(struct linked)))) {

或更好(不要施放 malloc):

if((pro[i] = malloc(sizeof(struct linked)))) {

否则当malloc失败时你告诉初始化成员

请注意,您也可以使用 calloc,在这种情况下,无需将成员初始化为 NULL:

 for (int i = 0; i < 32; i++) {
     pro[i] = calloc(1, sizeof(struct linked));
     if (pro[i] == NULL) // And always check the return
     {
         perror("calloc");
         exit(EXIT_FAILURE);
     }
 }

问题出在你的比较上:

if(!(pro[i] = (struct linked *) malloc(sizeof(struct linked)))) {
    pro[i]->Head = pro[i]->Tail = NULL;
}

只有在 malloc return NULL 时才会计算为真。因此,如果条件为真,则您正在尝试取消引用 NULL 指针。这会调用 undefined behavior,这意味着您的程序可能会或可能不会崩溃。

如果 malloc 不为 return NULL,则您想要分配给 pro[i]->Head。此外,无需转换 malloc 的 return 值。

if((pro[i] = malloc(sizeof(struct linked)))) {
    pro[i]->Head = pro[i]->Tail = NULL;
}