Posts

Showing posts from January, 2022

Link-time Memory Allocation in C

Imagine you have a series of callback functions that you want your program to execute at some point. Ideally you would like to iterate over an array of function pointers, calling each one in turn. The problem is that each callback might be in a different file, and the total number of callbacks might be subject to change. You might allocate memory for the array dynamically at runtime, but this incurs significant overhead. A better solution would be to allocate memory at compile time since the total number of callbacks is known and you would avoid the overhead of dynamic allocation. Such a solution is tedious because it requires you to count the number of callbacks and adjust the code every time you compile your program. One possible solution is link-time allocation. This involves placing a pointer to each callback in a special section and using linker variables to get the size of the section at link-time. The overhead of dynamic allocation and the tedium of static allocation are both av...