fix rare ENOSPC bugs, and some mem leaks