Fixed memory leak in some functions