Reputation: 29
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.
Upvotes: 0
Views: 202
Reputation: 121
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 ?
Yes, the variable you have declared in int* fortytwo_pointer()
is a local variable. This means the variable you have declared stores in a stack frame and at the end of this function, the variable is going to become freed and there's no a good address to dereference and that's why v
is a dangling pointer.
My suggestion to resolve this problem is allocating memory from heap by using some functions such as malloc()
or calloc()
. Functions delete all variables in stack, not heap.
So, you can write your code below :
int* fortytwo_pointer () {
int *v = (int*) malloc (sizeof(int));
if(v == NULL)
{
printf("An error occurred.\n");
getch();
}
*v = 42;
return v;
}
and finally, don't forget to free *v
pointer. You can free that by using free()
.
Upvotes: 0
Reputation: 1675
Yes, you do. As pointed out in the comments on your question, you cannot "check it" by using printf
. From the moment that the function stack is popped, you're dealing with undefined behavior.
Use valgrind
to run your program, and it will point out any read/write errors. Those may not cause your program to fail every time, but should be taken care of nonetheless. I'm sure your dangling pointer will show up in there, and valgrind
will be kind enough to show you the full trace of where each error occurs.
Upvotes: 3