How can I do automatic memory management in C?

In the allocation / freeing of C memory executed with malloc and free .

In C ++ memory allocation / deallocation, new and delete executed.

In C ++, there are several solutions for managing automatic memory , for example:

  • Smart pointers.
  • RAII (resource initialization)
  • Links and circular links
  • ...

But how can I do automatic memory management in C?

Are there any AUTOMATIC memory management solutions in C?

Are there any recommendations or something similar for C?

I want when I foget free a memory block:

  • My code does not compile

- or -

  • The memory is automatically freed.

And then I say: Oh, C is better than C ++, Java and C #. :-)

+7
source share
3 answers
+12
source

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 .

+2
source

For linux, I use valgrind. Sure, the original reason valgrind was collecting was the debugging of your code, but it does a lot more. It will even tell you where potentially erroneous code can be non-invasive. My own selection command is as follows.

 # Install valgrind. Remove this line of code if you already have it installed apt install valgrind # Now, compile and valgrind the C gcc main.c -Werror -fshort-enums -std=gnu11 -Og -g3 -dg -gdwarf-2 -rdynamic -o main valgrind --quiet --leak-check=yes --tool=memcheck -Wall ./main 

Hope this helps. ~ Happy coding!

0
source

All Articles