c - 为包含另一个struct数组的struct正确分配内存

Tom*_*Tom 6 c memory

我想为包含另一个名为的结构的数组的结构分配内存table.我发现当在最后指定函数的指针时,linkedObjects数组中的变量被破坏,所以我认为我对动态内存的处理是错误的.

这就是我现在这样做的方式:

typedef struct Object {
    void *key;
    struct Object *top;
    struct Object *next;
} Object;

typedef struct Table{
    Object *linkedObjects;
    size_t size, originalSize;
    HashFcn hfun;
    PrintFcn pfun;
    ComparisonFcn fcomp;
} Table;

TableP CreateTable(size_t tableSize, HashFcn hfun, PrintFcn pfun, ComparisonFcn fcomp)
{
    int i;
    struct Table *table = malloc(sizeof(table));
    if (table==NULL)
    {
        ReportError(MEM_OUT);
        return NULL;
    }
    table->linkedObjects = NULL;
    table->linkedObjects  = malloc(tableSize * sizeof(Object));

    for(i=0;i<tableSize;i++)
    {

        table->linkedObjects[i].next = malloc( MAX_IN_LIST*sizeof(Object) );
        table->linkedObjects[i].top = malloc( MAX_IN_LIST*sizeof(Object) );
        table->linkedObjects[i].key = NULL;
        table->linkedObjects[i].top->key = NULL;
        table->linkedObjects[i].next->key = NULL;

        if (table->linkedObjects[i].next == NULL)
        {
            ReportError(MEM_OUT);
            return NULL;
        }
    }

    table->size = tableSize;
    table->originalSize = tableSize;
    table->hfun = hfun;
    table->pfun = pfun;
    table->fcomp = fcomp;
    return table;
}
Run Code Online (Sandbox Code Playgroud)

编辑:我编辑了功能代码以反映答案:

TableP CreateTable(size_t tableSize, HashFcn hfun, PrintFcn pfun, ComparisonFcn fcomp)
{
    int i;
    struct Table *table = malloc(sizeof(table));
    if (table==NULL)
    {
        ReportError(MEM_OUT);
        return NULL;
    }
    table->linkedObjects = NULL;
    table->linkedObjects  = malloc(tableSize * sizeof(Object));

    if (table->linkedObjects == NULL)
    {
        ReportError(MEM_OUT);
        return NULL;
    }

    for(i=0;i<tableSize;i++)
    {
        table->linkedObjects[i].next = NULL;
        table->linkedObjects[i].top = NULL;
        table->linkedObjects[i].key = NULL;
    }

    table->size = tableSize;
    table->originalSize = tableSize;
    table->hfun = hfun;
    table->pfun = pfun;
    table->fcomp = fcomp;
    //printf("%p\n", table->hfun);
    return table;
}
Run Code Online (Sandbox Code Playgroud)

但是当我到达最后的作业点时,table->linkedObjects[0].key那个是空的,而值是0x0超限到一个值0x8048cc0.执行此行时会发生这种情况:

table->originalSize = tableSize;
Run Code Online (Sandbox Code Playgroud)

另一个编辑:确认它在最后一次调用中随机发生(不仅在上面的行中):

table->size = tableSize;
table->originalSize = tableSize;
table->hfun = hfun;
table->pfun = pfun;
table->fcomp = fcomp;
Run Code Online (Sandbox Code Playgroud)

n. *_* m. 5

struct Table *table = malloc(sizeof(table));

应该

struct Table *table = malloc(sizeof(Table));

我有时喜欢C.

`

  • 首先,`struct Table*table = malloc(sizeof(struct Table))`或`Table*table = malloc(sizeof(Table))`.下定决心并坚持下去.其次,我要说它应该是`struct Table*table = malloc(sizeof*table)`.不必使用时不要使用类型名称. (3认同)