简体   繁体   中英

Freeing void pointer causes segfault

I am getting a segfault when I free a void pointer...

I'm trying to make a dynamic and generic array, to store enemies in my game:

typedef struct EnemyPool {
    void** elements;
    unsigned int element_count;
    unsigned int element_capacity;
    unsigned int element_size;
} EnemyPool;

It's an array of void pointers.

I create the array like so:

pool->elements = malloc(pool->element_capacity * sizeof(void*));

And update like this:

pool->element_capacity *= 2;
pool->elements = realloc(pool->elements, pool->element_capacity * sizeof(void*));

I create new elements like this:

pool->elements[new_idx] = malloc(pool->element_size);

pool->element_size is correct, it's simply a sizeof to the type of element that this array is storing...

So why, when I do:

free(pool->elements[0]);

I get a segfault...

I think it's freeing too much memory, since the segfault doesn't come from the free function, it comes from glfwSwapBuffers , but only after calling this particular free - A similar thing happened when I overflowed a buffer previously, which is why I think it's freeing too much memory. The question is why?

The segfault had absolutely nothing to do with that free or corrupt memory: I was trying to access the pointer right after calling the free on it... I figured this out using Valgrind, as suggested by a commenter. I didn't actually know Valgrind existed until today, that was really helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM