diff --git a/gdk-pixbuf/io-ico.c b/gdk-pixbuf/io-ico.c
index ddb804c..b0a7b87 100644
--- a/gdk-pixbuf/io-ico.c
+++ b/gdk-pixbuf/io-ico.c
@@ -330,10 +330,8 @@ static void DecodeHeader(guchar *Data, gint Bytes,
 			return;
 		}
 
-		/* We know how many bytes are in the "header" part. */
-		State->HeaderSize = entry->DIBoffset + INFOHEADER_SIZE;
-
-		if (State->HeaderSize < 0) {
+		/* Avoid invoking undefined behavior in the State->HeaderSize calculation below */
+		if (entry->DIBoffset > G_MAXINT - INFOHEADER_SIZE) {
 			g_set_error (error,
 			             GDK_PIXBUF_ERROR,
 			             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
@@ -341,6 +339,9 @@ static void DecodeHeader(guchar *Data, gint Bytes,
 			return;
 		}
 
+		/* We know how many bytes are in the "header" part. */
+		State->HeaderSize = entry->DIBoffset + INFOHEADER_SIZE;
+
 		if (State->HeaderSize>State->BytesInHeaderBuf) {
 			guchar *tmp=g_try_realloc(State->HeaderBuf,State->HeaderSize);
 			if (!tmp) {
