Which of the following scenarios can lead to a dangling pointer?Marks : 1Negative Marks : 0Answer hereReturning a pointer to a local variable from a functionUsing malloc() for memory allocationAssigning a pointer to another pointerDeclaring a pointer inside main()
Question
Which of the following scenarios can lead to a dangling pointer?Marks : 1Negative Marks : 0Answer hereReturning a pointer to a local variable from a functionUsing malloc() for memory allocationAssigning a pointer to another pointerDeclaring a pointer inside main()
Solution
The scenario that can lead to a dangling pointer is "Returning a pointer to a local variable from a function".
Here's why:
-
A local variable is created on the stack when a function is called and it gets destroyed once the function call is over.
-
If you return a pointer to such a local variable, the pointer is pointing to a location that is no longer valid because the local variable doesn't exist after the function call is over.
-
This is what is known as a dangling pointer - a pointer that doesn't point to a valid memory location.
The other scenarios mentioned do not necessarily lead to a dangling pointer.
-
Using malloc() for memory allocation: This is a common way to allocate memory dynamically in C. If used correctly, it does not lead to a dangling pointer.
-
Assigning a pointer to another pointer: This is also a common operation in C. It does not lead to a dangling pointer unless the original pointer becomes a dangling pointer for some reason.
-
Declaring a pointer inside main(): This is a common way to declare a pointer. It does not lead to a dangling pointer as long as the pointer is used correctly.
Similar Questions
In which case does a pointer become a dangling pointer?Marks : 1Negative Marks : 0Answer hereWhen it is declaredWhen it is used to allocate memoryWhen the memory it points to is reallocatedWhen the memory it points to is deallocatedClearNext
Which of the following is not a consequence of using a dangling pointer?Marks : 1Negative Marks : 0Answer hereMemory leakSystem crashSegmentation faultNone of the mentioned options
In which case does a pointer become a dangling pointer?
Which of the following statements about dangling pointers is true?
What is the result of dereferencing a dangling pointer?Marks : 1Negative Marks : 0Answer hereThe program crashes.The pointer is set to NULL.The value at the memory location it points to.A compilation error.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.