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)
That is undefined behavior. Freeing the pointer just tells the OS that the memory allocated can be overwritten. The memory is still there.. for lack of a better word. But anything can happen.. it may print a for you now, at other times it could be another character or number because another program has written to that memory location... anything can happen.
For your last question.. a and b are just symbolic names to an address. Calling free on the address is important, so whether you do free(a) or free(b), you are grand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With