diff --git a/src/libexpr/parser.y b/src/libexpr/parser.y
index fe87734f2098d8c0cc6a399f1769ec94f5443989..ec07a01919711badc5a162b31cf9fdeb99871375 100644
--- a/src/libexpr/parser.y
+++ b/src/libexpr/parser.y
@@ -43,6 +43,26 @@ static Pos makeCurPos(YYLTYPE * loc, void * data)
 }
 
 #define CUR_POS makeCurPos(yylocp, data)
+
+
+/* Make sure that the parse stack is scanned by the ATerm garbage
+   collector. */
+static void * mallocAndProtect(size_t size)
+{
+    void * p = malloc(size);
+    if (p) ATprotectMemory(p, size);
+    return p;
+}
+
+static void freeAndUnprotect(void * p)
+{
+    ATunprotectMemory(p);
+    free(p);
+}
+
+#define YYMALLOC mallocAndProtect
+#define YYFREE freeAndUnprotect
+
  
 %}