Consider the following three C functions :
[PI] int * g (void)
{
int x= 10;
return (&x);
}
[P2] int * g (void)
{
int * px;
*px= 10;
return px;
}
[P3] int *g (void)
{
int *px;
px = (int *) malloc (sizeof(int));
*px= 10;
return px;
}
Which of the above three functions are likely to cause problems with pointers?
Answer: C
Correct answer: Only P1 and P2
P1 returns the address of a local variable. Its lifetime ends when the function returns, so the caller receives a pointer to storage that no longer belongs to it - a dangling pointer.
P2 never assigns px an address at all, then writes through it, which is an uninitialised pointer and undefined behaviour. P3 is correct: it obtains storage from malloc, which has allocated lifetime and survives the return. The caller must free it, but that is a responsibility rather than a fault.
Please log in or register to report this question.