4 ms·
That's true, and many libraries do this. However, it comes at the cost of an unnecessary heap allocation that wouldn't otherwise be necessary if not for this en
by trealira 2y ago
That's true, and many libraries do this. However, it comes at the cost of an unnecessary heap allocation that wouldn't otherwise be necessary if not for this encapsulation. If you want to do this, but allocate on the stack, you have to do something like this:
typedef struct Bleh Bleh_t;
size_t get_bleh_size();
void init_bleh(Bleh_t *, int);
int main(void) {
const size_t bleh_size = get_bleh_size();
Bleh_t *const bleh = alloca(bleh_size);
init_bleh(bleh, 3);
const int i = getFoo(bleh);
}
If you rewrite "init_bleh" to return the pointer it receives as the first parameter, you could hide it behind a macro:
#define make_stack_bleh(i) init_bleh(alloca(get_bleh_size()), (i))
Used like this:
Bleh *const bleh = make_stack_bleh(x);
One advantage of this approach is that you could change the layout of a Bleh without recompiling the other object files, as your compiled code makes no assumptions about the size or the layout of the struct (i.e. the field offsets into a struct aren't hardcoded into the machine code emitted).