implementing function pointer callbacks in C - advanced patterns on execution
I'm relatively new to this, so bear with me. I'm having trouble with function pointers in C, specifically when I attempt to use them as callbacks in my code. I have a simple structure to hold a function pointer and a function that takes a callback. Here's my implementation: ```c #include <stdio.h> #include <stdlib.h> typedef void (*callback_t)(int); typedef struct { callback_t func; } MyStruct; void myCallback(int value) { printf("Callback called with value: %d\n", value); } void executeCallback(MyStruct *s, int value) { if (s && s->func) { s->func(value); } else { printf("Callback not set or structure is NULL.\n"); } } int main() { MyStruct s; s.func = myCallback; executeCallback(&s, 42); return 0; } ``` When I run this code, I get the expected output, but when I change `s.func` to `NULL` before calling `executeCallback`, I would expect to see the "Callback not set or structure is NULL." message. Instead, I get a segmentation fault. Here's what I tried: 1. Ensured that `s` is not NULL before accessing `s->func`. 2. Checked that my function pointer assignment is correct and that `myCallback` is properly defined. 3. Used `gdb` to step through and confirm that `s` is valid when passed to `executeCallback`. I suspect there might be some undefined behavior occurring when I set `s.func` to `NULL`, but I need to pinpoint where. Can anyone guide to identify what might be going wrong? I'm compiling with `gcc` version 11.2.0 on Ubuntu 20.04. My development environment is Windows. How would you solve this? This is my first time working with C 3.10. This is my first time working with C stable. The stack includes C and several other technologies. Cheers for any assistance!