Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C memory management with more pointers to the same location

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)

like image 956
AR89 Avatar asked Jan 27 '26 03:01

AR89


1 Answers

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.

like image 66
Lews Therin Avatar answered Jan 28 '26 16:01

Lews Therin