unix: fix various memory leaks and undef behavior

Kindly suggested by `cppcheck`.

/cc @saghul