diff --git a/swig-interfaces/FXMemoryStream.i b/swig-interfaces/FXMemoryStream.i
index 613cd5d7b44bbc793475b18e77665f1922005ea5..82c4209d25b716cf483771ff5c095947042a2980 100644
--- a/swig-interfaces/FXMemoryStream.i
+++ b/swig-interfaces/FXMemoryStream.i
@@ -44,7 +44,7 @@ public:
         return self->open(save_or_load,data);
         }
       }
-  
+
     // Take buffer away from stream
     VALUE takeBuffer() {
       FXuchar* buffer;
@@ -54,19 +54,23 @@ public:
       FXFREE(&buffer);
       return result;
       }
-  
+
     /// Give buffer to stream
     void giveBuffer(VALUE str){
+      FXuchar* copy = NULL;
       Check_Type(str,T_STRING);
       FXuchar* buffer=reinterpret_cast<FXuchar*>(StringValuePtr(str));
       FXuval sp=RSTRING_LEN(str);
-      self->giveBuffer(buffer,sp);
+      if( FXMALLOC(&copy, FXuchar *, sp)) {
+        memcpy(copy, buffer, sp);
+        self->giveBuffer(copy,sp);
+        }
       }
   }
-  
+
   /// Get position
   FXlong position() const;
-  
+
   /// Destructor
   virtual ~FXMemoryStream();
   };