GeekInterview.com
Series: Subject: Topic:
Question: 181 of 267

What is a memory leak? How can we avoid it?

Asked by: hariprasadt | Member Since Jul-2006 | Asked on: Jul 10th, 2006

View all questions by hariprasadt

Showing Answers 1 - 4 of 4 Answers
Sabith

Answered On : Jul 10th, 2006

In computer science, a memory leak is a particular kind of unintentional memory consumption by a computer program where the program fails to release memory when no longer needed. The term is meant as a humorous misnomer, since memory is not physically lost from the computer, but rather becomes claimed but ignored due to program logic flaws. When we are allocating memory using new or malloc and then failing to deallocate the memory after its use within the application's life span, then the memory allocated earlier will become unusable for the application, there by making it a leak in the memory.

  
Login to rate this answer.
Sabith

Answered On : Jul 10th, 2006

A memory leak can be avoided by making sure that whatever memory has been dynamically allocated will be cleared after the use of the same. for example

int main()

{ char *myCharData[20];

for (int nLoop =0;nLoop < 20; ++nLoop) { myCharData[nLoop ] = new char[256];

strcpy(myCharData[nLoop],"SABITH");

.......

}

.........................

/*Some manipulations here using myCharData*/

/*Now here we have to clear the data. The place can vary according to ur program. This being a simple program,u can clear at the end*/

for(int nLoop =0;nLoop < 20; ++nLoop)
{

delete[] myCharData[nLoop ];

}

return 0;

}

  
Login to rate this answer.
Guest

Answered On : Jul 17th, 2006

When dynamic memory allocation is used extensively, memory leak may occur.It happens when first memory block is not deleted . However, the address is lost because the pointer contains the address of second block.The memory leak is unintentional occupied memory. It can de avoided by using delete statement.

example:

float *ptr=new float

*ptr=6.0;//Access first block

'Use delete statement --"delete ptr";Otherwise it will cause memory leak

ptr=new float

*ptr=7.0//Acess second block

  
Login to rate this answer.
DaisyWheel

Answered On : Jul 25th, 2006

To avoid memmory leaks you should use smart pointers.

  
Login to rate this answer.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

Related Open Questions

Ads

Connect

twitter fb Linkedin GPlus RSS

Ads

Interview Question

 Ask Interview Question?

 

Latest Questions

Interview & Career Tips

Get invaluable Interview and Career Tips delivered directly to your inbox. Get your news alert set up today, Once you confirm your Email subscription, you will be able to download Job Inteview Questions Ebook . Please contact me if you there is any issue with the download.