GeekInterview.com
  I am new, Sign me up!
 
GeekInterview.com  >  Interview Questions  >  Programming  >  C++
Go To First  |  Previous Question  |  Next Question 
 C++  |  Question 86 of 209    Print  
What is a memory leak? How can we avoid it?

  
Total Answers and Comments: 4 Last Update: July 25, 2006     Asked by: hariprasadt 
  
 Sponsored Links

 
 Best Rated Answer

No best answer available. Please pick the good answer available or submit your answer.
July 10, 2006 21:48:22   
Sabith        

RE: What is a memory leak? How can we avoid it?
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.
 
Is this answer useful? Yes | No
July 10, 2006 21:53:03   
Sabith        

RE: What is a memory leak? How can we avoid it?
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;

}

 
Is this answer useful? Yes | No
July 17, 2006 12:22:07   
       

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

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


 
Is this answer useful? Yes | No
July 25, 2006 03:11:10   
DaisyWheel        

RE: What is a memory leak? How can we avoid it?
To avoid memmory leaks you should use smart pointers.
 
Is this answer useful? Yes | No


 
Go To Top


 Sponsored Links

 
About Us -  Privacy Policy -  Terms and Conditions -  Contact -  Ask Question -  Propose Category -  Site Updates 

Copyright © 2005 - 2010 GeekInterview.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape