fix
diff --git a/ChangeLog b/ChangeLog
index 601790d..b648503 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,7 @@
+2005-09-14  Miklos Szeredi <miklos@szeredi.hu>
+
+	* Add memory cleanup on thread exit
+
 2005-09-13  Miklos Szeredi <miklos@szeredi.hu>
 
 	* Set umask to zero in fusexmp and fusexmp_fh, so that
diff --git a/lib/fuse_kern_chan.c b/lib/fuse_kern_chan.c
index 577d2e5..7f7d09d 100644
--- a/lib/fuse_kern_chan.c
+++ b/lib/fuse_kern_chan.c
@@ -17,6 +17,7 @@
 static int fuse_kern_chan_receive(struct fuse_chan *ch, char *buf, size_t size)
 {
     ssize_t res = read(fuse_chan_fd(ch), buf, size);
+    int err = errno;
     struct fuse_session *se = fuse_chan_session(ch);
 
     assert(se != NULL);
@@ -25,10 +26,10 @@
     if (res == -1) {
         /* EINTR means, the read() was interrupted, ENOENT means the
            operation was interrupted */
-        if (errno == EINTR || errno == ENOENT)
+        if (err == EINTR || err == ENOENT)
             return 0;
         /* ENODEV means we got unmounted, so we silenty return failure */
-        if (errno != ENODEV)
+        if (err != ENODEV)
             perror("fuse: reading device");
         return -1;
     }
@@ -43,6 +44,7 @@
                                size_t count)
 {
     ssize_t res = writev(fuse_chan_fd(ch), iov, count);
+    int err = errno;
 
     if (res == -1) {
         struct fuse_session *se = fuse_chan_session(ch);
@@ -50,9 +52,9 @@
         assert(se != NULL);
 
         /* ENOENT means the operation was interrupted */
-        if (!fuse_session_exited(se) && errno != ENOENT)
+        if (!fuse_session_exited(se) && err != ENOENT)
             perror("fuse: writing device");
-        return -errno;
+        return -err;
     }
     return 0;
 }
diff --git a/lib/fuse_loop_mt.c b/lib/fuse_loop_mt.c
index 478aae7..c0828f7 100644
--- a/lib/fuse_loop_mt.c
+++ b/lib/fuse_loop_mt.c
@@ -68,6 +68,7 @@
         return NULL;
     }
 
+    pthread_cleanup_push(free, buf);
     pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
     pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
 
@@ -99,6 +100,7 @@
         pthread_mutex_unlock(&w->lock);
         fuse_session_process(w->se, buf, res, w->ch);
     }
+    pthread_cleanup_pop(1);
 
     /* Wait for cancellation */
     if (!is_mainthread)