Question: Pointers often involve memory allocation. If the program does not release all allocated memory before exit, it causes a memory leak, leading to deteriorating system

Pointers often involve memory allocation. If the program does not release all allocated memory before exit, it causes a memory leak, leading to deteriorating system performance. The GNU program valgrind is a useful free tool for detecting whether a program would cause a memory leak.

You can execute the command

$ valgrind -h

to find out its usage. You can first test its usage using the lab6.cpp program discussed above:

$ valgrind ./lab6

Does lab6 cause any memory leakage?

Now consider the following simple program, testmem.cpp that uses pointers and memory allocation to link items together.

// testmem.cpp #include  using namespace std; class node { public: double data; // data node *next; // pointer to a node }; node *get_memory () { node *p = new node; p->next = NULL; return p; // returns pointer to a node } void insert ( node *p, double a ) { if ( p != NULL ) { p->data = a; p->next = NULL; } } void printAll ( node *p ) { while ( p != NULL ) { cout << p->data << ", "; p = p->next; } cout << endl; } int main() { node *head, *tail, *p; p = get_memory (); head = tail = p; // points to new node insert ( tail, 6.0 ); p = get_memory (); tail->next = p; // attach new node tail = tail->next; insert ( tail, 8.0 ); p = get_memory (); tail->next = p; // attach new node tail = tail->next; insert ( tail, 9.0 ); printAll ( head ); }

Compile the program to testmem and execute the program (i.e. $ ./testmem ) to see how it works. Then use valgrind to find out if it causes any memory leak:

 $ valgrind ./testmem 

From the information displayed, could you determine that testmem causes a memory leak? Try to understand how the program works then fix the memory leak problem by writing a function deleteAll that releases all allocated memory. This function should be called before the program terminates. Hint: Your function might be similar to the following:

 void deleteAll ( node *p ) { while ( p != NULL ) { node *temp = p; p = p->next; ...... } } 

Test your new program using valgrind again to make sure it does not cause memory leak.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!