Search code examples
cvectorvalgrind

Creating a vector results in memory leak in C


I am trying to create a vector in C, following is the struct declaration:

#define VECT_INITIAL_CAPACITY 4

typedef struct vect vect_t;

struct vect {
  char **data; // data is an array of strings             
  unsigned int size;      
  unsigned int capacity;   
}; 

I have a function that constructs a new empty vector, here is what I did:

vect_t *vect_new() {

  vect_t *v = (vect_t*) malloc(sizeof(vect_t));

  if (v == NULL) {
    return NULL;
  }

  // Allocate memory for data
  v->data = (char**) malloc(VECT_INITIAL_CAPACITY * sizeof(char*));
  if (v->data == NULL) {
    return NULL;
  }

  for (int i = 0; i < VECT_INITIAL_CAPACITY; i++) {
    v->data[i] = NULL;
  }

  // Initialize fields
  v->size = 0;
  v->capacity = VECT_INITIAL_CAPACITY;

  return v;
}

Valgrind tells me that the line v->data = (char**) malloc(VECT_INITIAL_CAPACITY * sizeof(char*)); caused memory leak. But I'm not sure how to fix this. Can anyone point out what caused the memory leaks?

Edit: Added my cleanup code below:

/** Free all the memories of the vector. */
void vect_delete(vect_t *v) {

  // Delete data first
  for (int i = 0; i < v->size; i++) {
    free(v->data[i]);
  }
  // Delete the vector
  free(v);
}

Solution

  • /** Delete the vector, freeing all memory it occupies. */
    void vect_delete(vect_t *v) 
    {
        if(v)
        {
            // Delete data first
            if(v -> data)
                for (size_t i = 0; i < v->capacity; i++)  //not v->size
                {
                    free(v->data[i]);
                }
            free(v -> data);  //missing
            // Delete the vector
            free(v);
        }
    }
    

    Some remarks:

    1. Use the correct type for sizes and indexes (size_t) not int or unsigned
    2. Use objects instead of types in sizeofs. vect_t *v = malloc(sizeof(*v));
    3. Do not cast the results of void * functions like malloc. If the code does not compile, then you use the wrong compiler (C++ one) to compile C code.