what is meant by memory leak and what is the concept of dangling pointer,inreference to question 4 of mcq pointers.
Pointers and dynamic memory allocation
Hello @anjalirai36,
- A memory leak occurs when programmers create a memory(Dynamic memory allocation) in heap and forget to delete it.
/
Example:
void f()
{
int *ptr = new int;/* Do some work */
return; /* Return without freeing ptr*/
}
/
To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.
void f()
{
int *ptr = new int;/* Do some work */
delete(ptr);
return;
}
- A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer.
void f()
{
int *ptr = new int;/* Do some work */
delete(ptr);
// No more a dangling pointer ptr = NULL;
return;
}
Hope, this would help.
Give a like, if you are satisfied.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.