-6

I want to know if I can see how the garbage collector in C or C++ works?

What is the algorithm behind it that selects the values in memory which are not in use?

Can anyone tell me how the GC works in C?

Mat
  • 202,337
  • 40
  • 393
  • 406
Kamal Kafkaesque
  • 57
  • 1
  • 2
  • 7

5 Answers5

5

C and C++ do not have garbage collection.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
4

There is no garbage collector in either language. At least, not as part of standard compliant implementations.

Note that C++ had language restrictions which made it hard to implement garbage collection. Some of those rules have been relaxed in the latest standard, C++11. So in principle it would be possible to implement a standards compliant c++ garbage collector now.

The standard approach in C++ is to use smart pointers to automatically manage memory.

There's an interesting article here, containing some useful links. From the comments you might be able to see how difficult it is to reconcile GC with idiomatic C++.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
3

Please check this paper / article: A garbage collector for C and C++ from Hans Boehm

Tobias Langner
  • 10,634
  • 6
  • 46
  • 76
2

Although there is no garbage collection support in standard C and C++, there is at least one popular and pretty portable implementation called the Boehm-Demers-Weiser conservative garbage collector.

Conservative garbage collectors work by assuming that everything that looks like a pointer is a pointer, even if it's, for example, an integer in reality. So, they can sometimes fail to reclaim an unreferenced object. Also, some tricks like xoring pointers can hide the pointers from them. But in my experience they seem to work pretty well in practice.

cyco130
  • 4,654
  • 25
  • 34
0

In C, garbage collection is completely manual; you need to keep track of anything allocated with malloc() or related functions so you can release it with free() once you're finished with it, and this will never be done automatically.

C++ is generally the same; you need to delete anything allocated with new (and delete[] any array allocated with new[]). However, this process can (and should) be partly automated by creating objects that manage dynamic resources, releasing them in their destructors. This technique is generally known as RAII, and the most common examples are the containers and smart pointers from the standard library.

Neither language has automatic garbage collection, or any way to determine whether any dynamic object is in use; you always need to manage dynamic resources yourself. There are some non-standard extensions to provide garbage collection, but I don't know anything about them.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644