Smart pointers in C? Why not?

The new C++ standard has smart pointers, which does the memory management for you but with some overhead. C does not support these and won’t be. All these things really do is control the scope of a variable. You’ll be able to get around the troubles of memory allocation by using the stack extensively, but you’ll always have to have preallocated space for that. To do that, you need to know the size of the allocation, so many *think* that C will never be able to have a reasonable replacement for this.

And I think what I’ve written up is reasonable, and that is why you are reading this.

First we need to decouple the allocation as an entity and its scope, these two can only be declared together in C, in other words; if you declare “int i”, i’s scope is what you declared it on. That’s bad and that’s where all the problems begin, because of this you can’t demote or promote i’s life span according to your needs, if this the declaration for some random data type that may grow or does not have a constant size; things get much worse.

What if what you declare controls the scope of your allocations? What if you can bind on to any arbitrary scope? Now things are just plain simple from here. You just place lists on random scopes and give them names, have all the pointers to the allocations go in to a list and when you want to free a scope just free the things in the list. If you want more control make more of these lists!

And here’s my implementation, it’s based on a linked list approach for the lists and has a few defines that the user should use,

mmdecl(varname) - varname is the name we give to the scope variable, do not use this name again and mmdecl is only a declaration it can be placed on the static part of an executable.

mminit(varname) - this is a define that wraps a routine, so it is not a declaration. You must place it in the code path.

mmalloc(varname, size) - this is what you use instead of malloc for custom mallocs please redefine malloc and free before you include mmanage.h to your project.

mmclean(varname) - the big clean up.

Source with Sample

Compile with

cc test.c mmanage.c