Answer to Question #144667 in C for Unknown

Question #144667
What is meant by memory leak and dangling pointer? Explain the concept with the help of example.
1
Expert's answer
2020-11-16T13:34:44-0500

Basically memory leak happens when a programmer allocates space for an element and forgets to delete it.

here is an example:

struct linkedListNode {
int data;
struct linkedListNode *next;
}; //structure of node
//here is an example of how to create a node in linkedlist
void insert()
{
struct linkedlist *newnode; //declaring the pointer to poin to newnode as soon as it created.
struct linkedlist *ptr;
int x; //for storing the data
printf("enter the element to be inserted\n");
scanf("%d",&x); // reading the integer
newnode=(struct linkedlist*)malloc(sizeof(struct linkedlist)); //allocating memory for new node
newnode->data=x; //inserting data into the node
newnode->next=NULL; //putting next of the current node to NULL.
/* some other code
*/
//here if we don't do free(newnode) that means we are not deleting the space for which we have used for something.
//it will create memory leak.
//In order to avoid it we need to use free(newnode) as soon as we have done with the node.
}


The basic definition of dangling pointer is a pointer pointing to a location which is already deleted.Here coming to linkedlist we can tell dangling pointer is a pointer which pointing to a node which is already deleted.

here is a the code for deleting a head(starting) node in linkedlist:

void delete()
{
struct linkedlist *ptr3,*ptr4;
if(start!=NULL)
{
ptr3 = start;//here we are using ptr3 as a temporary pointer to delete a head node;
start = start->next; //moving head pointer to point next node;
free(ptr3);//deleting the head node
//here if we do ptr4 = ptr3 ; then it is called dangling pointer;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS