As Juraj Blaho replied , you can use a garbage collection library such as the Boehm conservative garbage collector , but there are others: the Ravenbrook memory pool system , my (not backed up) Qish GC , Matthew Plant GC , etc.
And often you can write your own garbage collector specifically designed for your use case. You can use the methods mentioned in your question in C (smart pointers, reference counting), but you can also implement the GC label and scan, or copy the GC.
An important issue when coding your GC is tracking local pointer variables (to collect the collected data). You can save them in a local struct and merge them together.
I highly recommend learning more about GC, for example. GC Guide . Algorithms there are useful in many situations.
You can even configure your GCC compiler (for example, using MELT ) to add checks or generate code (for example, code for scanning local variables) for your specific GC implementation. Or you can use some preprocessor (like GPP ) for this
In practice, the GC Boehm is often quite good.
Note that the resource of some data is a property of the whole program. Therefore, it is better to think about GC very early in the development phase of your software.
We also note that reliable detection of memory leaks by static analysis of the source code is generally impossible ( undecidable ), since it can be equivalent to a problem with stopping .
Basile starynkevitch
source share