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?