在c中安全分配包含各种数组的结构

the*_*man 5 c dynamic-allocation

我的代码中有这样的东西

typedef struct ts_fem_mesh
{   
    double          **vertices;
    unsigned int    **triangles;
    unsigned int    n_ver;
    unsigned int    n_tri;
} fem_mesh;

fem_mesh *fem_mesh_new(unsigned int n_ver, unsigned int n_tri)
{
    fem_mesh *mesh;
    mesh = (fem_mesh *)malloc(sizeof(fem_mesh));

    mesh->n_ver = n_ver;
    mesh->n_tri = n_tri;

    mesh->vertices = (double **)calloc(n_ver, sizeof(double *));
    mesh->triangles = (unsigned int **)calloc(n_tri, sizeof(unsigned int *));

    int i;
    for(i=0;i<n_ver;i++)
        mesh->vertices[i] = (double *)calloc(2, sizeof(double));
    for(i=0;i<n_tri;i++)
        mesh->triangles[i] = (unsigned int *)calloc(3, sizeof(unsigned int));
    return mesh;

}
Run Code Online (Sandbox Code Playgroud)

通常情况下,当我打电话fem_mesh_new,我使用了非常大的数字n_vern_tri,这有时会导致分配错误(没有足够的空间).

即使我遇到这种错误,我的程序也应该建议用户并执行.在这种情况下,我想释放自错误点以来我分配的所有东西(即我在尝试分配时遇到错误mesh->triangles,但是mesh->vertices分配了,所以我想免费mesh->vertices)

有更简单的方法吗?我能想到的唯一方法(这是我想要避免的那个)就是填充我的许多if(x == NULL)的代码,但这很烦人,因为内存的分配顺序(每个我可以得到一个错误的地方,我应该编写代码,释放从那时起分配的所有东西).

不知道是否清楚,希望有人可以带来一些帮助:)

MBy*_*ByD 1

由于动态分配在每次分配中都可能失败,因此您应该检查每次使用它是否成功,即使这很烦人。但你只能做到三点:

mesh = (fem_mesh *)malloc(sizeof(fem_mesh));

之后mesh->triangles = (unsigned int **)calloc(n_tri, sizeof(unsigned int *));并检查这两个分配。

在循环之后,并检查循环。