I think hiding the definition of the structure makes the code more secure, because you use it with a compiler, which no member of the structure can access directly. The disadvantage is that users cannot declare structure type variables on the stack because the size of the structure is unknown, and sometimes it is advisable to avoid using malloc() . It can be (with partial success) using alloca(3) , which is present in all major libc implementations, although this function does not match POSIX. Given these small pros and cons, can such a design be considered good at all?
In lib.h :
struct foo; extern size_t foo_size; int foo_get_bar (struct foo *);
In lib.c :
struct foo { int bar; }; size_t foo_size = sizeof foo; int foo_get_bar (struct foo *foo) { return foo->bar; }
In example.c :
#include "lib.h" int bar(void) { struct foo *foo = alloca (foo_size); foo_init (foo); return foo_get_bar (foo); }
UPD . Updated a question that indicates that the idea of ββusing alloca() is to declare a structure on the stack, but hiding its definition.
c memory-management struct alloca
Alexander Solovets
source share