Memory management fixes and optimization.