0

I have a small code snippet for deleting element in linked list. Here is the code:

if (head->data ==  num) {
    delete head;
    head = head->next;
}

Can you please explain to me, why this code works. It deletes the head and sets the head to the next element.

When I saw this I thought that this will not work but it works.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
depecheSoul
  • 896
  • 1
  • 12
  • 29
  • 4
    Although it is not an exact duplicate but the concept is the same... Read this legendary answer by Eric Lippert http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794 – Aamir Jun 21 '12 at 11:11
  • 1
    I guess we now need a tag "why-does-this-work" – Vinayak Garg Jun 21 '12 at 11:13

3 Answers3

7

It's undefined behavior, so anything can happen, including appearing to work.

When you call delete, you're releasing the memory back to the OS. There's no guarantee that whatever is there is deleted or cleared. So the memory can remain the same as before the delete, but that's just by chance. Accessing it results in undefined behavior.

A proper approach for this would be:

if (head->data ==  num) {
    aux = head;
    head = head->next;
    delete aux;
}
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 1
    Could you explain why this ensures that the memory is released ? Also, are the rules same for C? i.e. `aux = head; head = head->next; free(aux)` ensures that memory is released ? – rajatkhanduja Jun 21 '12 at 11:15
  • 1
    @rajatkhanduja the memory is released in both cases. My code just doesn't run into undefined behavior, because you're no longer accessing an invalid pointer. - you can't access a pointer after you call `delete` on it. – Luchian Grigore Jun 21 '12 at 11:17
  • 2
    @rajatkhanduja, no, it's not just coding practice, really consider reading Eric Lippert's answer liked in the comments to your question. – unkulunkulu Jun 21 '12 at 11:22
2

OS could postpone invalidating of memory segment. You see it is not robust to delete tiny memory parts, what is more you could use only one memory segment, so it is more effective to delete it once.

tim-oleksii
  • 133
  • 9
0

It is not all advisable to access the data from the memory which is already deleted or freed. Some times it may work, but the behavior is undefined.

chanduthedev
  • 356
  • 2
  • 9