diff --git a/vncviewer/X11PixelBuffer.cxx b/vncviewer/X11PixelBuffer.cxx
index 548591e..bd0610c 100644
--- a/vncviewer/X11PixelBuffer.cxx
+++ b/vncviewer/X11PixelBuffer.cxx
@@ -186,7 +186,11 @@ int PlatformPixelBuffer::setupShm()
caughtError = false;
old_handler = XSetErrorHandler(XShmAttachErrorHandler);
- XShmAttach(fl_display, shminfo);
+ if (!XShmAttach(fl_display, shminfo)) {
+ XSetErrorHandler(old_handler);
+ goto free_shmaddr;
+ }
+
XSync(fl_display, False);
XSetErrorHandler(old_handler);