What is Memory Leak
A memory leak is a kind of resource consumption that occurs when the code does not manage memory allocations while creating the objects. So in order to manage it, the memory used by the object created should be released when not needed. For example, if you call a function or procedure where the object is created and not released then it goes on consuming memories due to multiple calls from the calling programme. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.
This could be a serious issue when the system or service is used for 24x7x365 without addressing it. If not handled it will slow down the system by consuming all resources and finally hangs the system.
How to solve it
There are several third party tools available but the simple solution solution is to release or free the used components or objects when not needed while exiting the funtion procedure.
Example:
procedure DoSomething;
var sl : TStringList;
begin
sl := TStringList.create()
try
try
// code that may raise exception
sl.Add('suren');
sl.Add('sujan');
except
ShowMessage('Error occured !');
end;
finally
// Free all memory used in this block
sl.free;
end;
end;
Note that there are two try blocks are used in above code. They are different and serve two different purposes. First try is used to make all objects free and the second try is used to trap the errors.
The finally
block will always be executed, even if there is no exception, while the except
block is only executed when there is an exception.
The finally
block is even executed when you exit the function early using Exit
in a try-finally
block.
The except
block is meant to handle the exception(s), while the finally
block is not. The finally
block is meant to contain code that should be executed regardless of an exception, i.e. mainly to protect resources. That is why you should do:
s := b.Create;
try
// Code that may raise an exception.
finally
s.Free; // Free resource, even if there was an exception.
// Exception is NOT handled.
end;
and:
try
// Code that may raise an exception.
except
// Handle the kind of exceptions you can handle.
end;
combined :
try
try
// code that may raise exception
except
// Handle Exception;
end;
finally
// Free all memory used in this block
end;
Note the finally block is not limited to memory management. It can be used for other actions like restoring/undo/close opened files, close open connections, shut down hardware that was started etc.