I was reading online about dangling pointers when I found the code on this link:
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.
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.)