CID#706118: possibly invalid cast
CID#705650: fix memory leak
CID#1157754: fix memory leak
CID#1157787: new[]/delete mismatch
CID#1158216: resource leak
Revert "cppcheck: reduce scope", CID#1158238

This reverts commit 943e2930e7453857f229efe04ade85cb1dc87faf.

That commit introduces memory corruption because the variables are still
used through a pointer.
CID#1157755 and CID#1157756: resource leaks
CID#1158520: use after free