Fix crashes when using stdin/stdout. Clean up memory leaks.