C Programming Reference >> C Programming Reference Question Bank >>
19/07/07 - Views - Ratings : 0 of 5 / Votes
Level - Begineer
Question -
Which functions of the below 3 functions misuses pointers and why?
int *f1(void)
{
int x =10;
return(&x);
}
int *f2(void)
{
int*ptr;
*ptr =10;
return ptr;
}
int *f3(void)
{
int *ptr;
ptr=(int*)
malloc(sizeof(int));
return ptr;
} |
Answer -
f1 and f2
Explanation -
You can observe here that all three functions have same signature and basically perform the same job. But thier is vital diffrence between the first two and the last one. First two returns a memmory address of a local variable whose memmory is assigned to it by a compiler and which may or maynot destroy it upon the exit of the function. The memmory location can also be used again by some other process for storing some other data. This memmory address is hence unreliable and should not be use and leads to a misuse of power of pointers when done.
Well third function also seems to be returnng a memmory location of a local variable but the diffrence here is that the memmory allocated is using dynamic memmory allocation functions and this memmory stays allocated till the dynamic memmory allocation function such as free is called to destroy it. So this memmory can be safely used. Also note that this memmory also gets automatically destroyed when program exits.
Reader Comments -
| An observer
|
Second function will cause Segmentation fault, because the pointer will have a garbage address which will be outside it's address space or protected address.
|
|