Fixes for some problems discovered by code analysis

Most of them are theoretical and/or unlikely to happen, but should not hurt to get them fixed.