无法使用 malloc 和 typedef

0 c malloc struct typedef

似乎不可能typedef在我的程序中使用和合并 malloc 函数:更具体地说:

组.h

#include "headers.h"
#include "info.h"
#include "sub_list.h"

typedef struct group_entity *group;

group new_group(int id);

void free_group(group group);
Run Code Online (Sandbox Code Playgroud)

组.c

#include "groups.h"

struct group_entity {
    int gId;
    info gFirst;
    info gLast;
    subinfo gSub;
};

group new_group(int id) {
    group new_group = malloc(sizeof(group));
    if (!new_group) {
        return NULL;
    }
    new_group->gId = id;
    new_group->gFirst = NULL;
    new_group->gLast = NULL;
    new_group->gSub = NULL;
    return new_group;
}


void free_group(group group) {
    free(group);
}
Run Code Online (Sandbox Code Playgroud)

头文件.h

#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>

#define MG 5 /* Length of Groups Array. */
Run Code Online (Sandbox Code Playgroud)

主程序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stddef.h>

#include "headers.h"
#include "groups.h"
#include "info.h"
#include "sub_list.h"

int main() {
    group new_object = new_group(5);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

每当我运行这段代码时,我都会因断点而停止

exe_common.inl - ln 297。

    if (!has_cctor)
        _cexit();
Run Code Online (Sandbox Code Playgroud)

我尝试free_group(group group)在 main.c 中使用一个函数 - 但似乎我遇到了断点。通过使用 VS 2019 调试器,我试图找出哪一行导致了错误。看来断点是在我的 main 执行后引起的。非常奇怪的行为,因为 main 甚至不会return 0

Kam*_*Cuk 5

Typedef 指针令人困惑。是指针的sizeof(group)大小而不是数据的大小。考虑对数据使用 typedef,并在使用指针的所有位置添加,以清楚地表明您正在使用指针。*

typedef struct group_entity group;
group *new_group(int id);
void free_group(group *group);

group *new_group(int id) {
    group *new_group = malloc(sizeof(group));
Run Code Online (Sandbox Code Playgroud)

或者,您可以执行sizeof(*new_group)sizeof(struct group_entity)