Fix resource leak and illegal memory access
Fix resource leak and illegal memory access

As reported by Coverity Scan

MaartenBent/matio,MaartenBent/matio,tbeu/matio,MaartenBent/matio,tbeu/matio,tbeu/matio,MaartenBent/matio,tbeu/matio