diff --git a/DynareFlex.ll b/DynareFlex.ll
index e64d6fc605e3d60f620e5fc33e278ac189451dc1..961326a82f496d12a9bdcb7c0d497869c8582778 100644
--- a/DynareFlex.ll
+++ b/DynareFlex.ll
@@ -407,11 +407,7 @@ int sigma_e = 0;
  /* Add the native statement */
 <NATIVE>.* { driver.add_native(yytext); BEGIN INITIAL; }
 
-<*><<EOF>> {
-             if (yylloc->begin.filename)
-               delete yylloc->begin.filename;
-             yyterminate();
-           }
+<*><<EOF>> { yyterminate(); }
 
 <*>.      { driver.error(*yylloc, "character unrecognized by lexer"); }
 %%
diff --git a/ParsingDriver.cc b/ParsingDriver.cc
index c0f2dc538529a659bee3da972cb362622b04a81e..1516a026a4f4c1894853f21e0eb33d289c12b6ee 100644
--- a/ParsingDriver.cc
+++ b/ParsingDriver.cc
@@ -71,6 +71,12 @@ ParsingDriver::parse(istream &in, bool debug)
 
   delete lexer;
 
+  /* Deleting filename in DynareFlex::yyterminate() is prematurate,
+     because if there is an unexpected end of file, the call to
+     ParsingDriver::error() needs filename */
+  if (location.begin.filename)
+    delete location.begin.filename;
+
   return mod_file;
 }