Sili Lai Sili Lai - 9 months ago 60
C Question

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

functions in

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:


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




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


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 *).