Why would freeing a pointer say p, which is assigned to where another pointer q points to, free q as well?
//for example,
int *p = malloc(sizeof(int));
*p = 10;
int *q = malloc(sizeof(int));
q = p;
free(p);
//This frees q as well.
Pointers q and p have different addresses but only point to the same location (i.e. to say that they store the same address which is of 10. Correct me if I'm mistaken there).
The contradiction most definitely arises in the way I think about pointers or in the way free() works because from all that I know (which is not a lot), since q and p have different addresses, freeing p should not affect q at all, unless I am wrong in understanding pointers, or that free()/memory works in a peculiar way.
I'd like to know why this is so. (I'm aware of the post Free an assigned pointer, but it doesn't explain why or how exactly this happens)
After
int *p = malloc(sizeof(int));
x
+----+
p --------> | |
+----+
P
is pointing to some x
memory which holds the some junk data.
*p = 10;
You are putting 10
into x
x
+----+
p --------> | 10 |
+----+
With below
int *q = malloc(sizeof(int));
y
+----+
q -------> | |
+----+
You created one more memory y
to which q
is pointing.
When you assign
q = p;
x
+----+
p --------> | 10 |
q --------> +----+
y
+----+
Memory leak | |
+----+
You made q
to point x
memory as well, losing the only reference to y
memory.
With freeing p
free(p);
p --------> (invalidated)
q -------->
y
+----+
Memory leak | |
+----+
You deleted x
memory thus p
and q
are pointing to freed memory.