Hello Stack Overflow! This is my first post, so please be gentle.
I've been playing around with C from time to time in the past. Now I've gotten to the point where I've started a real project (a 2D graphics engine using SDL, but that's irrelevant for the question), to be able to say that I have some real C experience. Yesterday, while working on the event system, I ran into a problem which I couldn't solve.
There's this typedef,
//the void parameter is really an SDL_Event*.
//but that is irrelevant for this question.
typedef void (*event_callback)(void);
which specifies the signature of a function to be called on engine events.
I want to be able to support multiple event_callbacks, so an array of these callbacks would be an idea, but do not want to limit the amount of callbacks, so I need some sort of dynamic allocation. This is where the problem arose. My first attempt went like this:
//initial size of callback vector
static const int initial_vecsize = 32;
//our event callback vector
static event_callback* vec = 0;
//size
static unsigned int vecsize = 0;
void register_event_callback(event_callback func) {
if (!vec)
__engine_allocate_vec(vec);
vec[vecsize++] = func; //error here!
}
static void __engine_allocate_vec(engine_callback* vec) {
vec = (engine_callback*) malloc(sizeof(engine_callback*) * initial_vecsize);
}
First of all, I have omitted some error checking as well as the code that reallocates the callback vector when the number of callbacks exceed the vector size.
However, when I run this code, the program crashes as described in the code. I'm guessing segmentation fault but I can't be sure since no output is given. I'm also guessing that the error comes from a somewhat flawed understanding on how to declare and allocate an array of pointers to function pointers.
Please Stack Overflow, guide me.