I was told by a rather smart person that you cannot implement garbage collection in C because of it’s weakly typed. The basic idea seems to be that C gives you too much freedom. He mentioned casting pointers without type checking…
I don’t really grok the idea. Can someone give me an explanation and possibly a code sample of why this wouldn’t work.
NOTE: Obviously C is about speed and why would you want to add garbage collection? I’m just curious really.
He probably referred to the fact that you can cast a pointer to an int and back to the original pointer type. It’s pretty much impossible for a GC to clean up correctly when you do that, consider:
EDIT: The above will only produce a dangling pointer with a precise GC. As others have pointed out, a conservative collector can still correctly handle this scenario as it assumes that any bit pattern that could be a valid pointer actually is a pointer and will thus not free the memory allocated. However, this is of course no longer possible when i is further modified such that it no longer looks like a valid pointer to the collector, e.g. as follows:
Moreover, (again as others have pointed out) it’s only impossible to implement a GC for C if you want to retain the full functionality of the language. If you refrain from using tricks like the above (i.e. you confine yourself to a subset of the possible operations) then GC is indeed feasible.