Mint Bee
Mint Bee

Reputation: 49

free pointer by other pointer points same memory

Is the code down below possible?

int *a_p = malloc(sizeof(int));
int *b_p = a_p;
free(b_p);         //Free a_b by using b_p
a_p = b_p = NULL;

I'm very confused because two pointers point same memory...

If that code is impossible, could you teach me why, please?

Upvotes: 0

Views: 278

Answers (2)

ikegami
ikegami

Reputation: 385839

What you have is perfectly fine.


  1. You create a_p, allocate a memory block, and assign the block's address to a_p.
    After int *a_p = malloc(sizeof(int));:

    int *a_p                  int @ 0x1234
    +------------+           +------------+
    | 0x1234     |           | ???        |
    +------------+           +------------+
    
  2. You create b_p with the same value as a_p.
    After int *b_p = a_p;:

    int *a_p                  int @ 0x1234
    +------------+           +------------+
    | 0x1234     |           | ???        |
    +------------+           +------------+
    
    int *b_p
    +------------+
    | 0x1234     |
    +------------+
    

    Notably, this didn't allocate any memory other than b_p itself.

  3. You free the memory block you previously allocated.
    After free(b_p);:

    int *a_p
    +------------+
    | 0x1234     |
    +------------+
    
    int *b_p
    +------------+
    | 0x1234     |
    +------------+
    
  4. You overwrite the addresses.
    After a_p = b_p = NULL;:

    int *a_p
    +------------+
    | NULL       |
    +------------+
    
    int *b_p
    +------------+
    | NULL       |
    +------------+
    

The two remaining blocks (a_p and b_p) have automatic storage duration, so they will be automatically freed when the function returns.

Upvotes: 3

MikeCAT
MikeCAT

Reputation: 75062

Pointers are values. They can be copied via assignment.

In this example, b_p is set to the value of a_p and then free(b_p); is called.

At that moment, the value in b_p is one in a_p, which is a pointer returned from malloc() and not yet freed. Therefore, this is valid.

Another possibility is that malloc() failed and NULL is returned, but free(NULL); is valid and defined to do nothing, so the code is valid also in this case.

Upvotes: 1

Related Questions