What are the feature of C Programming language that break the type-safety and prohibits practical garbage collection from being added to the language? Explain.
Firstly, I don’t understand the relationship between type-safety and garbage collection. I’d appreciate if someone can help me with that.
What are the feature of C Programming language that break the type-safety and prohibits
Share
You can do garbage collection in C. It is called conservative garbage collection. The trick is to treat any data that looks like a pointer as if it were in fact a pointer, and not reclaim any memory that is reachable through it. There are two problems: first, you cannot move data around (i.e., compaction), because of the uncertainty of whether something that looks like a pointer is in fact a pointer (so updating it to point to a new location could result in data corruption).
The type-safety problem is that it is possible for a C programmer to store a pointer to an int, perform math on it, and then restore the pointer (as in:
ptrdiff_t d = (ptrdiff_t) ptr; ptr = NULL; d += 42; /* GC here would be bad */ d -= 42;) This pointer hiding could lead a conservative garbage collector to prematurely reclaim memory that was only reachable through that pointer.