Add error test and fix memory leak, reported by Ashwini Sharma.
Don't close device handle until after calling flush ioctls, reported by Ashwini Sharma.
Fix more memory leaks reported by Ashwini Sharma.