簡體   English   中英

C calloc 和自由結構

[英]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 時,它會導致分段錯誤,我認為這是因為,雖然我將 memory 分配給了 d->pArray 和 calloc,大小為 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);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM