diff --git a/lib/client-handshake.c b/lib/client-handshake.c
index 86cc5ba18b12268eb6991597d5952c2c21f9c256..da52ea5438e2bd3006ea841aebe3e2201100110c 100644
--- a/lib/client-handshake.c
+++ b/lib/client-handshake.c
@@ -304,6 +304,10 @@ lws_client_connect_2(struct lws *wsi)
 
 oom4:
 	lws_free(wsi->u.hdr.ah);
+	wsi->u.hdr.ah = NULL;
+	/* take care that we might be inserted in fds already */
+	if (wsi->position_in_fds_table != -1)
+		goto failed;
 	lws_free(wsi);
 
 	return NULL;