Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If two pointers point to the same memory address, do you only need to use free(ptr) once or twice?

Say we have a struct...

struct node{
    int data;
    struct node *next;
};

struct node *new_node = malloc(sizeof(node));

struct node *temp_node = new_node;

If I use free...

free(temp_node);

Is new_node free as well (since the address no longer exists) or does new_node simply point to NULL (in which case I would need to free new_node as well) ?

Cheers!

like image 645
Jules Avatar asked Dec 23 '22 20:12

Jules


2 Answers

You don't free pointers but the memory block(s) that you allocated - whose address a pointer points to.

With malloc, it returns pointer to a chunk of memory allocated that looks like this:

             +--------+
             |        |
new_node --> | 0x1000 |
             |        |
             +--------+

If 0x1000 is the starting address of that block of memory, that's what new_node points to (i.e., new_node == 0x1000).

When you assign new_node to temp_node, temp_node points to the same block of memory (i.e., temp_node == 0x1000):

             +--------+
             |        |
new_node --> | 0x1000 | <-- temp_node
             |        |
             +--------+

But there's just one block of memory that you have allocated. So once you free it via either pointer, the other is automatically invalidated and you are no longer allowed access that block of via either pointer.

In the same way, you can assign it to any number of pointers but as soon as it's free'd via one pointer, it's done. That's why care is needed when copying pointers around (because if you free one, it may still be inadvertently used).

P.S.: Free'd pointer may or may not point to NULL afterwards - it's simply undefined behaviour to access free'd memory.

like image 189
P.P Avatar answered May 18 '23 20:05

P.P


The way to think about is like: pointers point to a memory location. free() returns memory pointed to by a pointer back to the system. Thus if you have two pointers - once free is called the memory is returned to the system. You still have two pointers. And they still point to the same memory location. It's just now it is not your memory but system's :)

In short - free as many times as you malloc'd.

like image 23
AbbysSoul Avatar answered May 18 '23 20:05

AbbysSoul