The C programming language has no built-in garbage-collection mechanism – and it very likely never will. This can (and does) lead to memory leaks by even the best programmers. It is also an imputes for the Rust language. However, depending on your use-case, it is still possible to structure your code to use the stack as a sort of zero-cost “garbage collector”.
Lets jump directly into the code!
This is how many applications instantiate and utilize a structure or arbitrary object.
struct resource *instance;
instance = malloc(sizeof(struct resource));
get_resource(instance); ... free(instance);
While this is a perfectly fine snippet of code, it requires the program to explicitly free(3)
instance when it is no longer needed or risk a memory leak. There is also a slight performance loss from the malloc(3) and free(3).
Therefore, lately I have been using another method.
struct resource instance;
Rather than allocating memory, this uses the stack. When the variable is “destroyed” immediately after falling out of scope without the need for a free(3).
The downside, of course, is losing the ability to pass the pointer elsewhere after the initial allocating function closes. But, this can be overcome by creating the variable in the parent function to all those that need it.