Why am I getting access to this pointer even after I’m free?

Asked

Viewed 126 times

4

I have this program and theoretically it was not to lose the address of new after giving the free making the same 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:

inserir a descrição da imagem aqui

When I try to access the new->numTeste, shouldn’t make a mistake ?

1 answer

10


The function free() does not prevent access to any address. Any attempt to access an address will be successful (all right, it has a protection exceptions, but it does not come to 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 appropriate and produces the intended result.

free() does not erase any data, it remains there until some operation writes over it. And the address will still be accessible even after that, only now it has a piece of data that’s not the same. Nothing informs you that you are wrong, if you are not careful you will cause problems, potentially serious. Not to mention the security failure.

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

So, contrary to what you might be imagining, the function malloc() 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 is like having 10 real in the wallet. There are only 10 real, there are 10 real that can only be used to pay for a sandwich in your Manuel’s bakery.

If you want guarantees look for a language with automatic memory management, or at least secure, it is not the case of C that is a powerful language, fast and flexible, not secure. Security is given by you.

  • I would just like to know why this is because I needed the released pointer to be equal to NULL (which I thought the function free() did), but even after releasing the memory, it means I can set the pointer new to NULL that will work ?

  • Yes, it will, and you can continue accessing the pointer, only you can no longer access the object, if you try it will give error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.