--- gd.c
+++ gd.c
@@ -147,6 +151,7 @@
   }
   memset (im, 0, sizeof (gdImage));
   if (overflow2(sizeof (int *), sy)) {
+    gdFree(im);
     return 0;
   }
   im->tpixels = (int **) gdMalloc (sizeof (int *) * sy);
@@ -2757,6 +2762,8 @@
     }
   bytes = (w * h / 8) + 1;
   im = gdImageCreate (w, h);
+  if (!im)
+    return NULL;
   gdImageColorAllocate (im, 255, 255, 255);
   gdImageColorAllocate (im, 0, 0, 0);
   x = 0;
--- gd_gd.c
+++ gd_gd.c
@@ -149,6 +149,8 @@
     {
       im = gdImageCreate (*sx, *sy);
     }
+  if (!im)
+    goto fail1;
   if (!_gdGetColors (in, im, gd2xFlag))
     {
       goto fail2;