Moved memory allocation closer to actual use to fix leaks

fixes some clang analyzer warnings about memory leaks of 'buf'
in all the early-return paths.
Removed two useless dead stores.

fixes some clang analyzer warnings