0

How can I determine dangling pointers in C? Here is example of this.

int *fun(void) {
    int i = 2;
    return &i;
}
Emil
  • 73
  • 1
  • 12
  • What do you mean determine? Decide if the return value of your `fun` is a dangling pointer or not? Or to pass/return the value (or address) of the `i` variable? – Emil Vatai Oct 27 '18 at 11:22
  • `i` is a local variable. It doesn't exist after `fun` returns, but you're returning a pointer to it. Same if you return a pointer to malloced memory but freed the pointer before returning it. Such pointers dangle. It isn't rocket science. – Petr Skocik Oct 27 '18 at 11:23
  • I meant return value of function is dangling pointer or not? – Emil Oct 27 '18 at 11:24
  • I got it. Thanks – Emil Oct 27 '18 at 11:25

1 Answers1

0

Here in below code block

int *fun(void) {
    int i = 2;
    return &i;
}

you are returning a address of a local variable that means you are returning a dangling pointer & it causes undefined behaviour, your compiler could have warned you like

error: function returns address of local variable [-Werror=return-local-addr]

     return &i;

above if you could have compile with flags like gcc -Wall -Wstrict-prototypes -Werror test.c

Achal
  • 11,821
  • 2
  • 15
  • 37