0

I have read that the name to object binding can have a longer lifetime than the object itself. According to my understanding, when the object is destroyed, then the binding between the name and the object is also gone. Then how can binding lifetime can be longer than object lifetime? Please explain using this example code in in C

char *p = malloc(4);
strcpy(p, "abc");
free(p); // object gone, but binding of p, to a useless address, lives on.
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Pavan_k_k
  • 309
  • 1
  • 5
  • 11
  • I think a good place to start would be reading about the stack vs. the heap: http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html – Craig Otis Oct 07 '15 at 01:08
  • 1
    I think you need to look at some higher level languages than C. You are much closer to the hardware here than you feel... – MK. Oct 07 '15 at 01:14

2 Answers2

0

The real answer to the question:

Then how can binding lifetime can be longer than object lifetime?

Is: "It can't". As you say, p still has a value, but it is unusable* so any "binding" must have been broken. "Binding" is kind of an odd way to look at this issue. I can sort of see where you are going, but I've never heard it used quite the way you are using it (in the context of C).

* By unusable I mean "undefined behavior" - it might work, but it's not reliable and there is never a good reason to try it (anyone who tells you otherwise is lying)

John3136
  • 28,809
  • 4
  • 51
  • 69
0

free(p); // object gone, but binding of p, to a useless address, lives on.

variable P holds memory address of some heap location. When you call free it returns the memory back to heap, but P still is pointing to that location unless someone override the value of p, using something like p = NULL. But if you do not change the value of P, then

1) It will hold value till the function scope if P defined inside function.

2) It will hold value till the lifetime of program if P is global variable.

Holding the address which have been freed does not make any sense. It equivalent to holding some junk data.

Ritesh
  • 1,809
  • 1
  • 14
  • 16