Fix memory leak and format files