Fixed detection of read errors. Added release allocated memory to avoid memory leaks.