From 7b9692529231c30f458560bd36b30a7bd30a8da9 Mon Sep 17 00:00:00 2001 From: Mingjie Shen Date: Sat, 20 May 2023 22:44:10 -0400 Subject: [PATCH] Fix integer overflow when calculating memory allocation size Allocating memory with a size controlled by an external user can result in integer overflow. Also, we need to check return values of malloc/calloc for null. --- src/rtextures.c | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/rtextures.c b/src/rtextures.c index 2d8056d64..d60a4c2c4 100644 --- a/src/rtextures.c +++ b/src/rtextures.c @@ -668,18 +668,25 @@ bool ExportImageAsCode(Image image, const char *fileName) // Generate image: plain color Image GenImageColor(int width, int height, Color color) { - Color *pixels = (Color *)RL_CALLOC(width*height, sizeof(Color)); - - for (int i = 0; i < width*height; i++) pixels[i] = color; - Image image = { - .data = pixels, + .data = NULL, .width = width, .height = height, .format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, .mipmaps = 1 }; + if (height > INT_MAX / sizeof(Color)) { + return image; + } + Color *pixels = (Color *)RL_CALLOC(width, height*sizeof(Color)); + if (pixels == NULL) { + return image; + } + image.data = pixels; + + for (int i = 0; i < width*height; i++) pixels[i] = color; + return image; }