cleanup: prevent leaks on error

Free memory on error. Be cautious about errno being overwritten by
intervening functions.

Lots more cleanup to be done, for example, check for double free's.