ProgrammingEmbedded C Developer

Describe how callback functions work and are implemented in C. How should these functions be declared and used when developing libraries or interacting with APIs?

Pass interviews with Hintsage AI assistant

Answer

Callback functions are functions whose addresses are passed as arguments to other functions. This allows for implementing event handlers, custom algorithms, and plugins.

Declaring a callback function:

  1. Describe the corresponding function pointer type:
typedef void (*callback_func_t)(int);
  1. Passing the handler function:
void process(callback_func_t cb) { // ... cb(42); // call the callback } void handler(int n) { printf("Processed number: %d\n", n); } int main() { process(handler); return 0; }

Tips:

  • Stick to explicit typedefs for pointer types; the code will be more readable.
  • Ensure that the callback function's signature matches the expected one.
  • Avoid passing local uninitialized or freed functions.

Trick question

Can a function with a non-matching signature be passed as a callback?

Common incorrect answer: "Yes, C will allow this if you declare an explicit cast."

Correct answer: Although formal casting is possible, calling such a function will lead to undefined behavior—incorrect values may be passed to parameters, and the stack may become corrupted.

Example of danger:

typedef void (*cb_t)(int); void wrong_cb(double d) { printf("%f\n", d); } void call(cb_t f) { f(123); } int main() { call((cb_t)wrong_cb); } // DANGEROUS: signatures differ

Examples of real errors due to lack of knowledge of the nuances of the topic


Story

In one embedded project, the sorting function received a pointer to a function with too narrow a signature as a compare function. This led to sorting errors and memory corruption due to incorrect parameter passing.

Story

In a graphics engine library, an event mechanism based on callbacks was implemented, but some callbacks accidentally referenced local functions from already freed dynamic libraries, causing crashes when hitting invalid addresses.

Story

When developing a cross-platform system, the author incorrectly defined the calling convention for callback functions. This did not manifest on one OS but caused the program to crash on another when calling callbacks from the C library.