Search code examples
cstructfree

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);
}

when i test the DestoryCustomerDB it makes segmentation fault, I think it is because, Although I allocated the memory to d->pArray with calloc, size d->curArrsize, for loop in DestoryCustomerDB iterates forever. why this happen?

and am i doing freeing correctly? Thank you,


Solution

  • for (p = d->pArray; p != NULL; p = nextp) { can fail as there is no certain p == NULL.

    Iterate to curArrSize instead.

      while (d->curArrSize > 0) {
        struct UserInfo *p = d->pArray[--(d->curArrSize)];
        free(p->id);
        free(p->name);
      }