Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Experience with dangling refereces or memory leaks. If you have experience with

ID: 3889017 • Letter: E

Question

Experience with dangling refereces or memory leaks. If you have experience with a language like C, C++, or Pascal, in which dynamically allocated space must be manually reclaimed, describe your experience with dangling references or memory leaks. How often do these bugs arise? How do you find them? How much effort does it take? Learn about open source or commercial tools for finding storage bugs (Valgrind is a popular open source example). Do such tools weaken the argument for automatic garbage collection?

Explanation / Answer

1) Memory leak
   occurs when we create a memory in heap using malloc in c and new in c++ and forget to delete them after there use. Memory leaks are serious issues for programs please see the below memory leak example

/* Function with memory leak */
void fun()
{
   int *ptr = (int *) malloc(sizeof(int));

   // Done some work .....
   // .....

   return; // Returning without freeing the memory
}

To avoid memory leaks, memory allocated on heap should always be freed.
/* Function without memory leak */
#include <stdlib.h>;

void fun()
{
   int *ptr = (int *) malloc(sizeof(int));

   // Done some work .....
   // .....


   free(ptr);
   return;
}

2) Dangling pointer :
   A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer.

/* Main Function with Dangling pointer */
int main()
{
    int *ptr = (int *)malloc(sizeof(int));

    // After below free call, ptr becomes a
    // dangling pointer
    free(ptr);
   
}


/* Main Function without Dangling pointer */
   int main()
{
    int *ptr = (int *)malloc(sizeof(int));

    // After below free call, ptr becomes a
    // dangling pointer
    free(ptr);
   
    // No more a dangling pointer
    ptr = NULL;
}

Valgrind is a popular tool to detect memory leaks.

/* code with memory leak */

#include <stdio.h>

#include <stdlib.h>

int main()

{

    int *ptr = (int*)malloc(50);

    return 0;

}

when run with valgrind tool show the memory leak of 50 bytes as shown below:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote