Amir Saniyan
Amir Saniyan

Reputation: 13779

How can I do automatic memory management in C?

In C memory allocation/deallocation done by malloc and free.

In C++ memory allocation/deallocation done by new and delete.

There are some solutions in C++ for automatic memory management like:

But how can I do automatic memory management in C?

Is there any solutions for AUTOMATIC memory management in C?

Is there any guidelines or something like that for C?

I want when I foget free a block of memory:

-- or --

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

Upvotes: 9

Views: 5153

Answers (3)

Jack G
Jack G

Reputation: 5351

For linux, I use valgrind. Sure, the original reason for why valgrind was build was to debug your code, but it does a lot more. It will even tell you where potentially erroneous code could be in a non-invasive way. My own command line of choice 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!

Upvotes: 1

Juraj Blaho
Juraj Blaho

Reputation: 13471

You may use a Boehm garbage collector library.

Upvotes: 12

As answered by Juraj Blaho, you can use a garbage collection library, such as the Boehm conservative garbage collector, but there are other ones : Ravenbrook's memory pool system, my (unmaintained) Qish GC, Matthew Plant's GC, etc...

And often, you can write your own garbage collector specialized for your use case. You could use in C the techniques mentioned in your question (smart pointers, reference counting), but you can also implement a mark & sweep GC, or a copying GC.

An important issue when coding your GC is to keep track of local pointer variables (to garbage collected data). You could keep them in local struct and chain them together.

I strongly suggest to read more about GC, e.g. the GC handbook. The algorithms there are useful in many situations.

You could even customize your GCC compiler (e.g. using MELT) to add checks or to generate code (e.g. code to scan local variables) for your particular GC implementation. Or you could use some pre-processor (e.g. GPP) for that

In practice, Boehm's GC is often good enough.

Notice that liveness of some data is a whole-program property. So it better to think about GC very early in the design phase of your software development.

Notice also that detecting reliably memory leaks by static source code analysis is in general impossible (undecidable), since it can be proven equivalent to the halting problem.

Upvotes: 3

Related Questions