diff --git a/common/rfb/Password.cxx b/common/rfb/Password.cxx
index 240c9d4..cf9362e 100644
--- a/common/rfb/Password.cxx
+++ b/common/rfb/Password.cxx
@@ -55,7 +55,7 @@ PlainPasswd::~PlainPasswd() {

 void PlainPasswd::replaceBuf(char* b) {
   if (buf)
-    memset(buf, 0, strlen(buf));
+    memset(buf, 0, length ? length : strlen(buf));
   CharArray::replaceBuf(b);
 }

diff --git a/common/rfb/util.h b/common/rfb/util.h
index b678b89..fffe322 100644
--- a/common/rfb/util.h
+++ b/common/rfb/util.h
@@ -50,16 +50,21 @@ namespace rfb {
     CharArray() : buf(0) {}
     CharArray(char* str) : buf(str) {} // note: assumes ownership
     CharArray(int len) {
+      length = len;
       buf = new char[len];
     }
     ~CharArray() {
-      delete [] buf;
+      if (buf) {
+        delete [] buf;
+        buf = nullptr;
+      }
     }
     void format(const char *fmt, ...) __printf_attr(2, 3);
     // Get the buffer pointer & clear it (i.e. caller takes ownership)
     char* takeBuf() {char* tmp = buf; buf = 0; return tmp;}
-    void replaceBuf(char* b) {delete [] buf; buf = b;}
+    void replaceBuf(char* b) {if (buf) delete [] buf; buf = b;}
     char* buf;
+    int length = 0;
   private:
     CharArray(const CharArray&);
     CharArray& operator=(const CharArray&);
