pointers-memory · intermediate · ~15 min
Index and invoke function pointers safely from a jump table with bounds verification.
Virtual machines, emulator decoders, and command interpreters use function pointer jump tables instead of large switch statements to achieve $O(1)$ dispatch.
Implement:
typedef int (*opcode_handler_t)(int a, int b);
int dispatch_opcode(uint8_t opcode, int a, int b, opcode_handler_t *table, size_t table_len);
table == NULL, return -999999.opcode >= table_len, return -999999 (invalid opcode).table[opcode] == NULL, return -999999 (unimplemented opcode).table[opcode](a, b) and return its result.opcode_handler_t ops[4] = { add, sub, mul, NULL };
dispatch_opcode(0, 10, 5, ops, 4); // returns 15 (add)
dispatch_opcode(3, 10, 5, ops, 4); // returns -999999 (NULL handler)
dispatch_opcode(5, 10, 5, ops, 4); // returns -999999 (out of bounds)
opcode: byte index; a, b: integer operands; table: array of function pointers; table_len: table size.
Returns handler result or -999999 on error.
C11 freestanding. Safe function pointer invocation.
#include <stdint.h>
#include <stddef.h>
typedef int (*opcode_handler_t)(int a, int b);
/* Execute table[opcode](a, b). If opcode is out of bounds, table is NULL,
or handler is NULL, return -999999. */
int dispatch_opcode(uint8_t opcode, int a, int b, opcode_handler_t *table, size_t table_len) {
(void)opcode; (void)a; (void)b; (void)table; (void)table_len;
return -999999;
}
Invoking table[opcode] without checking for NULL; off-by-one check on table_len.
opcode >= table_len; table[opcode] == NULL; table == NULL; valid handler returning negative.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.