gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:23:01 26 4
gpt4 key购买 nike

我想为一个结构分配内存,该结构包含另一个名为 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;
}

编辑:我编辑了函数代码以反射(reflect)答案:

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;
}

但是当我到达最后的赋值点时,table->linkedObjects[0].key 为空且值为 0x0 得到了溢出值 0x8048cc0。执行此行时会发生这种情况:

table->originalSize = tableSize;

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

table->size = tableSize;
table->originalSize = tableSize;
table->hfun = hfun;
table->pfun = pfun;
table->fcomp = fcomp;

最佳答案

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

应该是

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

我有时喜欢 C。

`

关于c - 为包含另一个结构数组的结构正确分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14032674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com