0

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?

Mint Bee
  • 49
  • 1
  • 3
  • 10
  • 2
    Yes, it is possible. – MikeCAT Dec 06 '20 at 07:29
  • Thank you so so so much! Appreciate you! – Mint Bee Dec 06 '20 at 07:36
  • 1
    A few links that provide basic discussions of pointers may help. [Difference between char *pp and (char*) p?](https://stackoverflow.com/a/60519053/3422102) and [Pointer to pointer of structs indexing out of bounds(?)...](https://stackoverflow.com/a/60639540/3422102) (ignore the titles, the answers discuss pointer basics) – David C. Rankin Dec 06 '20 at 07:47
  • Some function for exemple with a void ** parameter can allocate memory you must free. – Florent Dec 06 '20 at 08:32
  • Yes, it is possible, both pointers point to the same allocated buffer, so any of them (but not both) can be used to `free()` the allocated buffer. – Luis Colorado Dec 07 '20 at 17:52

2 Answers2

3

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518
1

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.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70