On one hand, if I write the following code :
int* fortytwo_pointer () {
int v = 42;
return &v;
}
I get a dangling pointer and I can check this by calling
printf ("forty two : %d\n", *(fortytwo_pointer()));
On the other hand
int* copy (int *pointer) {
return pointer;
}
int* fortytwo_pointer () {
int v = 42;
return copy (&v);
}
does not produce the same 'Segmentation fault' error.
I would expect it to also be an instance of a dangling pointer because the value v
goes out of scope just the same. Is it true ? If so, how to check that the pointer is indeed dangling ?
Edit : This question is more focused on dynamically checking that a pointer is valid, for example if we get a pointer from a call of a library function. I'm more interested in checking if the code could produce invalid pointers.