Revert "Revert "corrected memory errors""

This reverts commit 2bf92f1dd7b9efe88c55ff138d88dba38193d525.