From d5e893fcb45ebbf55954417002ca4baeddccc81e Mon Sep 17 00:00:00 2001 From: Jason Yundt Date: Fri, 10 May 2024 08:31:56 -0400 Subject: [PATCH] Prevent potential uninitialized memory access MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before this change, cf_OpenLibrary() did something along the lines of this: char id[4]; fread(id, 4, 1, fp); strncmp(id, "HOG2", 4); If fread() finishes successfully, then that code is fine. However, fread() might encounter an error or bump into the end of a file. In those scenarios, the value of id will not necessarily be initialized [1]. In other words, when fread() fails, strncmp() might operate on uninitialized memory. This change makes sure that the value of id only gets used if fread() succeeds. Additionally, this change fixes a GCC warning about ignoring fread()’s return value. [1]: --- cfile/cfile.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cfile/cfile.cpp b/cfile/cfile.cpp index 8918ebea..064dfb00 100644 --- a/cfile/cfile.cpp +++ b/cfile/cfile.cpp @@ -147,8 +147,7 @@ int cf_OpenLibrary(const char *libname) { mem_free(lib); return 0; // CF_NO_FILE; } - fread(id, HOG_TAG_LEN, 1, fp); - if (strncmp(id, HOG_TAG_STR, HOG_TAG_LEN)) { + if (!fread(id, HOG_TAG_LEN, 1, fp) || strncmp(id, HOG_TAG_STR, HOG_TAG_LEN)) { fclose(fp); mem_free(lib); return 0; // CF_BAD_FILE;