我想为一个结构分配内存,该结构包含另一个名为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;
}
编辑:我编辑了功能代码以反映答案:
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
get的溢出到一个值0x8048cc0
。执行此行时会发生这种情况:
table->originalSize = tableSize;
另一个编辑:确认它在最后一次调用中随机发生(不仅在上面的行中):
table->size = tableSize;
table->originalSize = tableSize;
table->hfun = hfun;
table->pfun = pfun;
table->fcomp = fcomp;