From ad9dfb2bd167f00b43fda83404a1528946473d54 Mon Sep 17 00:00:00 2001
From: a <e>
Date: Thu, 24 Aug 2023 21:03:31 +0300
Subject: [PATCH] (RIN forum) updated and safer impl for
 Local_Storage::load_image_resized() "for those cases where it might fail to
 allocate memory for the resized image" by RIPAciD:
 https://cs.rin.ru/forum/viewtopic.php?p=2884627#p2884627

---
 dll/local_storage.cpp | 36 ++++++++++++++++++------------------
 1 file changed, 18 insertions(+), 18 deletions(-)

diff --git a/dll/local_storage.cpp b/dll/local_storage.cpp
index 0f2bb570..5a772b1a 100644
--- a/dll/local_storage.cpp
+++ b/dll/local_storage.cpp
@@ -793,27 +793,27 @@ std::vector<image_pixel_t> Local_Storage::load_image(std::string const& image_pa
 
 std::string Local_Storage::load_image_resized(std::string const& image_path, std::string const& image_data, int resolution)
 {
-    int width, height;
-    char *resized_img = (char *)malloc(sizeof(char) * 184 * 184 * 4);
-    unsigned char* img;
+    std::string resized_image(resolution * resolution * 4, 0);
+    char* resized_img = (char*)malloc(sizeof(char) * resolution * resolution * 4);
+    PRINT_DEBUG("Local_Storage::load_image_resized: %s for resized image (%i)\n", (resized_img == nullptr ? "could not allocate memory" : "memory allocated"), (resolution * resolution * 4));
 
-    if (image_path.length() > 0)
-    {
-        img = stbi_load(image_path.c_str(), &width, &height, nullptr, 4);
-
-        if (img != nullptr)
-        {
-            stbir_resize_uint8(img, width, height, NULL, (unsigned char *)resized_img, resolution, resolution, NULL, 4);
-            stbi_image_free(img);
+    if (resized_img != nullptr) {
+        if (image_path.length() > 0) {
+            int width, height;
+            unsigned char* img = stbi_load(image_path.c_str(), &width, &height, nullptr, 4);
+            PRINT_DEBUG("Local_Storage::load_image_resized: \"%s\" %s\n", image_path.c_str(), (img == nullptr ? stbi_failure_reason() : "loaded"));
+            if (img != nullptr) {
+                stbir_resize_uint8(img, width, height, NULL, (unsigned char*)resized_img, resolution, resolution, NULL, 4);
+                resized_image = std::string(resized_img, resolution * resolution * 4);
+                stbi_image_free(img);
+            }
         }
+        else if (image_data.length() > 0) {
+            stbir_resize_uint8((unsigned char*)image_data.c_str(), 184, 184, NULL, (unsigned char*)resized_img, resolution, resolution, NULL, 4);
+            resized_image = std::string(resized_img, resolution * resolution * 4);
+        }
+        free(resized_img);
     }
-    else if (image_data.length() > 0)
-    {
-        stbir_resize_uint8((unsigned char *)image_data.c_str(), 184, 184, NULL, (unsigned char *)resized_img, resolution, resolution, NULL, 4);
-    }
-
-    std::string resized_image(resized_img, resolution * resolution * 4);
-    free(resized_img);
 
     reset_LastError();
     return resized_image;