memory management fixes

The first 7 patches in this pull request are the patches attached to RT #3198. The rest are fixes for similar memory management issues (mostly missing frees and missing null checks) elsewhere in the source code.