Question:
What is a memory leak? How can we avoid it?
Answer:
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;
Source: CoolInterview.com
memory leak - when we allocate memory dynamically and somehow lose the way to reach that memory.
ex: void fun() { int *ptr = new int; }
void main() { fun(); } here the pointer ptr is local to the function fun(); which dies when control returns from the function.so we loose the way to reach that address, but the dynamically allocated memory would continue to remain allocated.
the easiest way to avoid memory leak is to place the pointers inside objects and let the objects manage them. Source: CoolInterview.com
Answered by: Monalisha Nayak | Date: 6/15/2009
| Contact Monalisha Nayak
Memory leaks happens for the memory allocated on Heap(ex A *temp = new A()) . memory allocated by us on stack (int a) is released automatically when the function returns or module goes out of scope.
But memory allocated on heap will not be freed automatically, we need to release it manually.
ex:
func() { A *a = new A(); //on heap int b; // on stack }
main() { func(); }
Now in above example when func is called memory for "a" is created on HEAP by using NEW, but it is not freed by using DELETE, hence is memory leak. On the other hand "b" is created on STACK & freed automatically. so correct implementation is:
func() { A *a = new A(); //on heap int b; // on stack delete a; //deleting memory on heap }
main() { func(); } Source: CoolInterview.com
Answered by: Nitin | Date: 4/11/2010
| Contact Nitin
If you have the better answer, then send it to us. We will display your answer after the approval.
Rules to Post Answers in CoolInterview.com:-
- There should not be any Spelling Mistakes.
- There should not be any Gramatical Errors.
- Answers must not contain any bad words.
- Answers should not be the repeat of same answer, already approved.
- Answer should be complete in itself.
|