Fixed memory leak.
Added test cases