I just started to learn C and was wondering if there's something like Java's GC.
Sorry if this question is too basic. The answers I found were too technical for me.
An explanation, in simple terms...
CodePudding user response:
As long as you don't use new
you should have garbage collection automatically.
Manage allocated memory by only using make_unique
and make_shared
for unique_ptr
and shared_ptr
respectively.
CodePudding user response:
Ok, here is my take on the subject. You could try Hans Boehm conservative GC and it should (well, famous last words) work just fine with C .
When we allocate object via new in C , first we call new operator to get raw memory, and then we execute new expression which does object initialization, calling constructors etc. Look here for the discussion, but in the nutshell, Boehm GC replaces the global ::new operator with calls to GC API.
Global ::detele operator is also replaced with what is basically empty call - GC will reclaim memory back. Delete expression will be the same and whole RAII machinery should just work.
It is well written and decent piece of software, and if I would need GC for C project, this is the place where I would start.