Search code examples
cfunction-pointersfree

Why is this code causing invalid pointer?


I have a C++ background and am a newbie in C. I wanted to write a generic vector in C. Things were fine until I decided to add a free function to delete each elements. But now the program will crash while running the free() functions in vectorFree().

I have not test free function yet, I just pass NULL and the vector already cannot work. The vector worked well before I add the free function feature.

Here is my codes, I omit all the comments and irrelevant codes:

vector.h

typedef void (*FreeFunction)(void *element);

typedef struct Vector {
    void *elements;
    ...
    FreeFunction freeFunc;
} Vector;

Vector* vectorAlloc(size_t elemSize, VectorFreeFunction freeFunc);
void vectorFree(Vector *vector);

...

vector.c

Vector* vectorAlloc(size_t elemSize, VectorFreeFunction freeFunc)
{
    Vector* vector = malloc(sizeof(vector));
    ...

    vector->elements = malloc(elemSize * vector->capacity);
    ...

    vector->freeFunc = freeFunc;
    return vector;
}

void vectorFree(Vector *vector)
{
    if (vector->freeFunc != NULL) {
        for (int i = 0; i < vector->size; i++) {
            vector->freeFunc(vectorAt(vector, i));
        }
    }

    free(vector->elements);
    free(vector);
}

...

vectorTest.cpp

void test()
{
    Vector* num = vectorAlloc(sizeof(int), NULL);
    vectorFree(num);
}

Solution

  • This line is a problem, because it does not allocate enough memory:

    Vector* vector = malloc(sizeof(vector));
    

    It should be either

    Vector* vector = malloc(sizeof(Vector));
    

    (with capital V) or

    Vector* vector = malloc(sizeof(*vector));
    

    (with an asterisk *).