Reference counting GC in languages with pointer arithmetic
I was wondering if it is possible to implement reference counting-based GC in languages which allow pointer arithmetic. For example (this is pseudo-C),
int* f()
{
in开发者_如何学JAVAt array[5] = { 1, 2, 3, 4, 5 };
int *ptr = array + 3;
return ptr;
}
Will it be ever possible for a compiler to manage memory correctly in this scenario?
No, it's not possible in general. Suppose you use the XOR trick to implement linked lists; then the pointers are still around "implicitly" (can be reconstructed), but the GC cannot find them without knowledge of how the XOR trick works and when it is being used. It may think the number of references is zero for each element. To trick a GC that does have knowledge of the XOR trick, devise a variant by e.g. including some kind of salt in the XOR.
Also, consider how reference-counted C would have to handle this:
void *ptr = WHATEVER; // first reference
uintptr_t ptr_temp = ptr; // second reference
unsigned char ptr_copy[sizeof(uintptr_t)];
memcpy(ptr_copy, ptr_temp, sizeof(uintptr_t)); // third reference
Every general-purpose GC for C/C++ uses heuristics to cope with pointer arithmetic tricks. See, for example, the conservative GC of Hans Boehm. Conservative means here that it considers just about everything a potential pointer.
精彩评论