fix resource leak, coverity issue 1198844
check for invalid parameter, coverity issue 1198843, also reformat source