How can I do automatic memory management in C?

Viewed 4195

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:

  • Smart Pointers.
  • RAII (Resource Acquisition Is Initialization)
  • Reference counting and cyclic references
  • ...

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:

  • My code doesn't compile

-- or --

  • Memory automatically deallocated

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

3 Answers

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!

Related