Improve memory management to avoid leaks.