Search code examples
cpointersmemoryfree

C Memory allocation, overwriting after freeing


I am stuck on a question about memory allocation, particularly what happens after the free() statements. So for example, when I free a and then change its address, will a still have its old value or will it get the address of the b? Does a become a dangling pointer because I adjust it after I free it? Is the output simply going to be a and b with the same values, z-20 and w=9? I'd appreciate any help. Thank you very much!

int* t = (int*) malloc(sizeof(int)); 
int* b = (int*)    malloc(sizeof(int)); 
int* a = (int*) malloc(sizeof(int)); 
int w;
int z;

*a = 11;
*b = 9;
z = *a + *b; 
w = *b;
*a = z; 
free(a);

*t = 4;
b = &z;
a = b; 
free(t);

printf("Printed results are:\n");
printf("*a=%d, *b=%d, z=%d, w=%d\n", *a, *b, z, w);

Solution

  • when I free a and then change its address, will a still have its old value or will it get the address of the b

    It will get the pointer value in b, which is the address of z.

    The code should free b before reassigning it to the address of z:

    free(b);
    b = &z;
    

    otherwise I don't see a problem with the code, as it doesn't appear to be dereferencing any freed pointers.

    output

    It is what you would expect:

    *a=20, *b=20, z=20, w=9