Using C, is there a safer way to allocate memory than using malloc? For example, is there a C equivalent of a smart pointer, or some handy function that someone has come up with that makes the process of allocation a little cleaner? I mean, sure, it’s only one line anyway, but there must be a more concise way to get it done. I suppose the deallocation portion of this question is included in whether there is something similar to a smart pointer in C.
Share
The process of allocation seems enough clear: each malloc-ed block should be free-ed. The simplest next step (before GC) that comes into mind to me is to write a function that “tracks” your allocation, so that at the exit of your code/function you can free everything you need no more in a single function call (and of course another function allows to free single block as usual). This would add a little bit of memory usage, but once implemented properly would make it easier to free blocks allocated one by one in one single shot.
The usage would be something like:
This should at least assure that everything allocated “in” the “pool” is free-ed with
mempool_destroy, so in the worst usage you could just alloc everything with the “pool” mechanism, and free everything when you don’t need it anymore (e.g. at the exit of a function). (Likely “pool” is not an appropriate name)