Why am I having access to this pointer even after giving free?

3

I have this program and theoretically was not to lose the address of new after giving the free making it inaccessible?

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int numTeste;
}strPt;


int main (){
    strPt * new;
    new = (strPt*) malloc(sizeof(strPt));
    new->numTeste = 4;
    printf("Endereço new: %p\n",new);
    printf("Numero na struct: %d\n",new->numTeste);
    free(new);
    printf("Endereço new: %p\n",new);
    printf("Numero na struct: %d\n",new->numTeste);
    return 0;
}

The result was this:

When I try to access new->numTeste , should not it give an error?

    
asked by anonymous 30.03.2018 / 03:32

1 answer

8

The free() function does not prevent access to any addresses. Any attempt to access an address will be successful (alright, it has a protection exception, but that's not the case for this example).

C is a language that does not prohibit you from accessing undesirable data. If you want to access an address it will be accessed, no matter if you have what you want or not, it is your responsibility to ensure that access is adequate and produces the desired result.

free() does not delete any data, it stays there until some operation writes over it. And the address will remain accessible even after this, but now it has a data that is not the same. Nothing informs you that you are wrong, if you do not take care it will cause problems, potentially serious. Not to mention failed security.

The only thing the function does is to tell the memory manager that the address can be used for something else when you need it.

So, unlike what you might be imagining, the malloc() function does not create a pointer, just reserves a space in memory and returns a pointer to that address. This pointer is just an address, it has nothing special. It's like having 10 reais in your wallet. It's only 10 reais, not 10 reais that can only be used to pay for a sandwich at your Manuel's bakery.

If you want guarantees look for a language with automatic, or at least safe, memory management, this is not the case with C being a powerful, fast and flexible, unsecured language.

    
30.03.2018 / 03:46