Correctly treat error case and memory management when reading certificate