commit c26ec63e7dbcfe19a769b5cc50f6f7af2e69025e
parent cbe5b2bd9d843800f426e134543211b225c0b214
Author: Eduardo Fontana Lazzari <edufonlaz@gmail.com>
Date: Thu, 29 Jan 2026 11:48:16 +0100
Fix: verify stream is not null before trying to close it
During prop rad parsing, fclose was called directly on the stream, which
could lead to a segfault if the stream was non-existent due to an error
in fopen.
Simply fix it by checking that stream is not NULL before trying to close
it. Also, add a test that verifies the correct behavior.
Diffstat:
2 files changed, 26 insertions(+), 3 deletions(-)
diff --git a/src/sphin_spectral_property.c b/src/sphin_spectral_property.c
@@ -135,6 +135,8 @@ parse_spectral_property
ASSERT(NULL != filename);
ASSERT('\0' != filename[0]); /* filename can't be empty */
+ str_init(sphin->allocator, &line);
+
stream = fopen(filename, "r");
if (NULL == stream) {
ERROR(sphin, "Not possible to open file %s -- %s\n",
@@ -143,8 +145,6 @@ parse_spectral_property
goto error;
}
- str_init(sphin->allocator, &line);
-
res = spectral_property_create(sphin, filename, &property);
if (RES_OK != res) { goto error; }
@@ -201,8 +201,10 @@ parse_spectral_property
}
exit:
- fclose(stream);
str_release(&line);
+ if (NULL != stream) {
+ fclose(stream);
+ }
if (NULL != txtrdr) {
txtrdr_ref_put(txtrdr);
}
diff --git a/src/test_sphin_load_prop_rad.c b/src/test_sphin_load_prop_rad.c
@@ -302,6 +302,26 @@ test_prop_rad_api_bad_formatting
CHK(sphin_load(sphin, path, &config) == RES_BAD_ARG);
}
+static void
+test_prop_rad_api_non_existing_file
+ (struct sphin* sphin)
+{
+ struct sphin_config* config = NULL;
+ const char* path = "file.txt";
+ FILE* fp = NULL;
+
+ CHK(fp = fopen(path, "w+"));
+ fprintf(fp, "#Mot Clé Nom\n");
+ fprintf(fp, "volume: \"reaction volume\"\n");
+ fprintf(fp, "\tprop_rad: SCATTERER \"name\"\n");
+ fprintf(fp, "\t\tconcentration: 1.935 mol/m^3\n");
+ fprintf(fp, "\t\tcross_sections:\n");
+ fprintf(fp, "\t\t\tabs_cross_sec: non_existing_file.txt nm m^2/part\n");
+ fclose(fp);
+
+ CHK(sphin_load(sphin, path, &config) == RES_BAD_ARG);
+}
+
int
main(int argc, char** argv)
{
@@ -321,6 +341,7 @@ main(int argc, char** argv)
test_prop_rad_api_unsorted_wavelengths(sphin);
test_prop_rad_api_missing_data(sphin);
test_prop_rad_api_bad_formatting(sphin);
+ test_prop_rad_api_non_existing_file(sphin);
CHK(sphin_ref_put(sphin) == RES_OK);
CHK(mem_allocated_size() == 0);