如果我注释掉ml_add(),代码工作正常,但是当该函数运行时,第一个项目完成但第二个迭代在bucket = list->buckets[bin];
函数的ml_add()
处遇到分段错误。我在那里做错了吗?
int main() {
FILE *fPtr = fopen("S.txt", "r");
MList *ml = ml_create();
printf("Creation OK\n\n");
MEntry *m2;
int i = 1;
while ((m2 = me_get(fPtr)) != NULL) {
unsigned long int hash = me_hash(m2, ml->numbuckets);
printf("Index: %d, Hash: %d\n", i, hash);
ml_add(&ml, m2);
me_print(m2, fPtr);
i++;
}
return 0;
}
/* ml_create - creates a new mailing list
- returns pointer to start of mailing list*/
MList *ml_create(void) {
MList *ml = malloc(sizeof(MList));
ml->numbuckets = NUMBUCKETS; // random initial number
// will increment once a bucket is full
ml->buckets = calloc(ml->numbuckets, sizeof(Bucket));
// init Buckets
int b;
for (b=0; b<ml->numbuckets; b++) {
ml->buckets = malloc(sizeof(Bucket));
Bucket *bk = malloc(sizeof(Bucket));
bk->size = 0;
bk->entries = calloc(BUCKETSIZE, sizeof(MEntry));
ml->buckets[b] = bk;
printf("***Bucket %d with capacity %d set at size %d\n",
b, BUCKETSIZE, ml->buckets[b]->size);
}
return ml;
}
int ml_add(MList **ml, MEntry *me) {
printf("***ml_add() called\n");
// get [ml]
MList *list = *ml;
// get hash of [me] -- index of bucket to add to
unsigned long int bin = me_hash(me, list->numbuckets);
printf("***hash/bin acquired: %d\n", bin);
// add to list's bucket[bin]
Bucket *bucket;
if ( (bucket = malloc(sizeof(Bucket))) == NULL)
printf("malloc failed.\n");
bucket = list->buckets[bin];
printf("***bucket %d acquired, size = %d\n", bin, bucket->size);
// add to end of bucket
bucket->entries[bucket->size] = malloc(sizeof(MEntry));
printf("*****malloc ok\n");
bucket->entries[bucket->size] = me;
printf("***Add to bucket %d at index %d ok\n", bin, bucket->size);
bucket->size++;
printf("***Bucket %d size now: %d\n\n", bin, bucket->size);
}