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;
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.