I was playing with this code:
#include <stdlib.h>
#include <stdio.h>
void function(int *p){
free(p);
}
int main(){
int *i = calloc(3, sizeof(int));
function(i);
i[0] = 'a';
printf("%c\n", i[0]);
return 0;
}
I expected to get an error, but instead it printed ‘a’, if ‘a’ is deallocated why does it print it? What happens in function(int *p) has any effect if the main()?(if you can, explain what happen to that ‘p’ pointer)
Suppose that I have those two in the same function:
int *a = malloc(...);
int *b = a;
Both of them point to the same piece of memory, but when I have to free it, should I call free on both of them, or just one of them?(again explain why if possible)
You have returned the memory to the heap, but the memory isn’t reused yet. So, sometimes the memory contents remain the same and you can read and write it as if it where still in use.
But you should never use memory that is already freed, since there’s no guarantee how long the memory stays this way.
In your second part
a = malloc(...); b = a, both variables point to the very same memory. Since this is just one piece of bytes, you mustfree()it exactly once. Otherwise you have a double free, which might corrupt the heap.Update for @SSHThis’s question:
free(a)only returns the memory to the heap. It doesn’t modifyaorb. The checkif(a)orif(b)evaluates to true, whether the memory was freed or not. Only when you setaorbto null, will the check evaluate to false, whether the memory was freed or not.So
free(a)andif(a)are independent operations. They don’t influence each other.