I saw this bit of code in another thread
void foo {
int *n = malloc(sizeof(int));
*n = 10;
n++;
printf("%d", *n);
}
The mistake here is obvious. n isn’t being dereferenced.
There is a memory leak.
Let’s assume there is a garbage collector working here. The reference count to our initial value of n is zero now because n isn’t referencing it anymore. So it’s garbage and returned back. But what about the new location pointed by n? Technically this area of memory hasn’t been allocated yet. So will the reference count be incremented here?
A correctly implemented garbage collector would work as follows:
Everything’s fine here.
This statement lets
pipoint behind the allocated int, which is explicitly allowed by the ISO C99 standard (see 6.5.6p7, 6.5.6p8). Later in the code, there may bepi--, so the allocated int can still be accessed. Or it may be accessed by the expressionpi[-1], which is perfectly valid at this point.At this point, there is no way to ever access the allocated int anymore, so the garbage collector may collect the memory.
In summary: All pointers that point either to the beginning of an object, to somewhere in the middle of that object or to the location behind that object can be used to access the object. So if such a value exists in memory, the object must not be garbage collected.