我希望为一个包含另一种名为
下面是我的处理方式:
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
的值为 null
,而且数值为 0x0
的时候,它会被覆盖成 0x8048cc0
。这发生在执行以下代码的时候:
table->originalSize = tableSize;
另外说明:已确认这种情况会随机出现在最后几次呼叫(不仅是在上一行):
table->size = tableSize;
table->originalSize = tableSize;
table->hfun = hfun;
table->pfun = pfun;
table->fcomp = fcomp;
top
和next
是神秘的。它们有什么作用?为什么要为每个变量分配一个数组,并且只初始化第一个对象的一个字段?除此之外,我没有看到这段代码有什么明显的问题。错误很可能在其他地方。但是,如果 MAX_IN_LIST 为 0 的话,那就是错的。 - n. m.next
和top
是指向其他类型为object
的对象的指针。 - Tom