5 ms·
Would that gc scheme potentially cause the following (pseudo) code to break? x = malloc(1); // allocates block 'a' in memory int i = (int) x; x = 0; i
by rand_r 15y ago
Would that gc scheme potentially cause the following (pseudo) code to break?
x = malloc(1); // allocates block 'a' in memory
int i = (int) x;
x = 0;
i = i - 1;
// gc runs here and frees 'a'
*( (int*)(i + 1) ) = 123; // failure
- pcwalton 15y agoYou'd have to insert a call to "malloc" to get the GC to run, but yes, it can break in that situation. (The classic example is an XOR-packed linked list being corrupted by the Boehm GC.) But note that isn't really fair to conservative GC, as no GC, precise or not, can cope with hidden pointers like that. So your example isn't really a strike against Go.
- smanek 15y agoI don't think any GC scheme could work with that. Languages that allow pointer arithmetic like that basically can't be GC'd. The problem with an imprecise GC is that having an integer that looks like a pointer, could prevent an object from being freed.
- pcwalton 15y agoAlmost — C# has a cool feature whereby you can do pointer arithmetic if you pin the objects in question first, so the GC won't collect or move them. (The language statically enforces this by forbidding you from taking the address of a value until you pin it.)
- derleth 15y agoThat's cool; I think another way of doing it is to allow programs to request a sandbox where the GC doesn't go so they can do all of the pointer-arithmeticking they want as long as all their pointers fall within the sandbox by the time they're written through or dereferenced.
- deleted 15y ago[deleted]
- deleted 15y ago[deleted]
- singular 15y agoIn Go, you'd have to be using the unsafe package and some gnarliness to cast between the allocated pointer and int, so you just wouldn't be able to do this in vanilla Go.
- ianlancetaylor 15y agoWhen Go gets a precise collector, simple implementations of this will work. Doing this kind of thing in Go requires importing the "unsafe" package, and any memory allocations done by code importing "unsafe" could be marked as possibly a pointer. However, it would probably be possible to write code involving two packages, one of which does not import "unsafe", to lead to dangling pointers and eventual crashes. That is why you should be careful about code that imports "unsafe".
- pcwalton 15y agoActually, the code sample in the grandparent comment obfuscates the memory address by subtracting 1. Even a conservative GC will be confused in this case...
- ianlancetaylor 15y agoAh, yes, missed that. Nothing a GC can do about code like that. At least it remains true that this can only happen in Go if you explicitly import "unsafe".