Search code examples
cdangling-pointer

How is this a dangling pointer?


I was reading online about dangling pointers when I found the code on this link:

http://www.billioncodes.com/c/ques-and-ans/747-what-is-dangling-pointer-give-an-example-on-pointers-to-pointer-and-passing-by-address

I'll paste it here:

#include <stdio.h>
void f(int *j)
{
    (*j)++;
}
int main()
{
    int i = 20;
    int *p = &i;
    f(p);
    printf("i = %d\n", i);
    return 0;
}

How is this a dangling pointer, and which pointer is dangling? The code looks valid to me. It should print "i = 21" and return. I don't see any dangling pointer.


Solution

  • There is no dangling pointer in that program.

    p is initialized to point to i. Both p and i have exactly the same lifetime; p ceases to exist at the same time that i does (on leaving the nearest enclosing block).

    j, the int* parameter in the function f, points to i (it's initialized to the value of the argument p, which points to i). The lifetime of j is limited to the execution of the block in the function f; i's starts after i's lifetime begins and ends before i's lifetime ends.

    The program should print i = 21. No dangling pointers, no undefined behavior. (int main() should be int main(void), but that's a minor point.)