C calloc 和 free struct
C calloc and free struct
#define UNIT_ARRAY_SIZE 1024
struct UserInfo {
char *name;
char *id;
int purchase;
};
struct DB {
struct UserInfo *pArray;
int curArrSize;
int numItems;
};
DB_T CreateCustomerDB(void) {
DB_T d;
d = (DB_T) calloc(1, sizeof(struct DB));
if (d == NULL) {
fprintf(stderr, "Can't allocate a memory for DB_T\n");
return NULL;
}
d->curArrSize = UNIT_ARRAY_SIZE; // start with 1024 elements
d->pArray = (struct UserInfo *)calloc(d->curArrSize,
sizeof(struct UserInfo));
if (d->pArray == NULL) {
fprintf(stderr, "Can't allocate a memory for array of size %d\n",
d->curArrSize);
free(d);
return NULL;
}
return d;
}
void
DestroyCustomerDB(DB_T d)
{
if (d == NULL) return;
struct UserInfo *p;
struct UserInfo *nextp;
for (p = d->pArray; p != NULL; p = nextp) {
nextp = p + 1;
free(p->id);
free(p->name);
}
free(d->pArray);
free(d);
}
当我测试 DestoryCustomerDB 时它会出现分段错误,
我认为这是因为,虽然我用 calloc 将内存分配给 d->pArray,大小为 d->curArrsize,
DestoryCustomerDB 中的 for 循环永远迭代。为什么会这样?
我的释放方式正确吗?谢谢,
for (p = d->pArray; p != NULL; p = nextp) {
可能会失败,因为没有确定的 p == NULL
。
改为 curArrSize
。
while (d->curArrSize > 0) {
struct UserInfo *p = d->pArray[--(d->curArrSize)];
free(p->id);
free(p->name);
}
#define UNIT_ARRAY_SIZE 1024
struct UserInfo {
char *name;
char *id;
int purchase;
};
struct DB {
struct UserInfo *pArray;
int curArrSize;
int numItems;
};
DB_T CreateCustomerDB(void) {
DB_T d;
d = (DB_T) calloc(1, sizeof(struct DB));
if (d == NULL) {
fprintf(stderr, "Can't allocate a memory for DB_T\n");
return NULL;
}
d->curArrSize = UNIT_ARRAY_SIZE; // start with 1024 elements
d->pArray = (struct UserInfo *)calloc(d->curArrSize,
sizeof(struct UserInfo));
if (d->pArray == NULL) {
fprintf(stderr, "Can't allocate a memory for array of size %d\n",
d->curArrSize);
free(d);
return NULL;
}
return d;
}
void
DestroyCustomerDB(DB_T d)
{
if (d == NULL) return;
struct UserInfo *p;
struct UserInfo *nextp;
for (p = d->pArray; p != NULL; p = nextp) {
nextp = p + 1;
free(p->id);
free(p->name);
}
free(d->pArray);
free(d);
}
当我测试 DestoryCustomerDB 时它会出现分段错误, 我认为这是因为,虽然我用 calloc 将内存分配给 d->pArray,大小为 d->curArrsize, DestoryCustomerDB 中的 for 循环永远迭代。为什么会这样?
我的释放方式正确吗?谢谢,
for (p = d->pArray; p != NULL; p = nextp) {
可能会失败,因为没有确定的 p == NULL
。
改为 curArrSize
。
while (d->curArrSize > 0) {
struct UserInfo *p = d->pArray[--(d->curArrSize)];
free(p->id);
free(p->name);
}