Although I don't know about a good, lightweight, and efficient GC for C, I would like to weigh some thoughts.
For many years I avoided heap allocations, fearing memory leaks. And I don't know how to get a memory leak without allocating from the heap.
But I do not know a better way to return memory from a function (for example, a string or an array of structures) than by allocating a heap. Heap allocation allows you to precisely allocate the amount of memory you need without knowing how much memory you need at compile time. If your program loads files into memory, you probably won't know at compile time how much memory you may need. If you are sending a static memory route, you always need to allocate the maximum memory you will ever need. Then your program can become a memory swamp when it is not necessary. A bunch of better.
But then tracking heap allocations can be difficult in some types of programs, for example, in a program in which there are many modules that insert and remove elements from the database in memory. And memory leaks can be so hard to solve. A good GC seems like a very good way to stop a memory leak due to automated tracking and freeing from heap.
So this post responds to the comment that "If you have problems with C using malloc () and free () correctly, you should switch to another language." If the programming problem is complex and the solution needs heap allocation, even the best programmers will have to debug memory leaks.
In some programs, there may be an alternative to using the garbage collection: you can assume that the operating system will release all program distributions when the program terminates. Thus, your main program may be able to invoke a second program that uses heap allocation, then writes the results to a file and exits. I tested this on windows. I noticed that Windows freed up the heap memory that my test program allocated to complete the test program. I have run a test program many times. There was no decrease in available memory.
Of course, having a second program that runs for a short time and ends is often not a viable solution.
source share