Fix some bugs discovered by coverity scan