diff -ruNa a/src/bin/readstat.c b/src/bin/readstat.c
--- a/src/bin/readstat.c	2023-02-20 20:09:24.000000000 +0100
+++ b/src/bin/readstat.c	2024-02-02 17:41:51.463409738 +0100
@@ -397,8 +397,6 @@
         module->finish(rs_ctx->module_ctx);
     }
 
-    free(rs_ctx);
-
     if (error != READSTAT_OK) {
         if (file_exists) {
             fprintf(stderr, "Error opening %s: File exists (Use -f to overwrite)\n", output_filename);
@@ -406,9 +404,14 @@
             fprintf(stderr, "Error processing %s: %s\n", rs_ctx->error_filename, readstat_error_message(error));
             unlink(output_filename);
         }
+
+        free(rs_ctx);
+
         return 1;
     }
 
+    free(rs_ctx);
+
     return 0;
 }
 
