From 71b97498cbe21c1e2d822dc602e0a807bf96e383 Mon Sep 17 00:00:00 2001 From: Daniel Schlaepfer Date: Mon, 18 May 2020 15:05:46 -0400 Subject: [PATCH] Fix function `_read_soil_line` (#495) - addressing #495 - The function was checking that the soil layer number was not larger than the number of soil layers for a gridcell - However, this check was carried out before handling the case where the input file provided only a cell number from where to copy to entire soil profile - In that case, the variable holding the soil layer number did not have a specified value and it may be a large value depending on the compiler --> if a compiler assigned a large value for the initialized soil layer number but not for the. number of soil layers, then the check incorrectly indicated a bad input file --> this commit separates the checks for cell number from the check for soil layer number and places the check for soil layer number after the code affirmed that it is currently working with soil layer inputs --> also added a check to make sure the the cell number from which to copy an entire soil profile does exist --- ST_grid.c | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 5c853686..be99300b 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1025,14 +1025,28 @@ static int _read_soil_line(char* buf, SoilType* destination, int layer){ &destination->pclay[layer], &destination->imperm[layer], &destination->soiltemp[layer], destination->rootsFile); - if(cellNum > grid_Cells || layerRead > destination->num_layers){ - LogError(logfp, LOGFATAL, "%s: cells out of order or too many layers.", grid_files[GRID_FILE_SOILS]); + if(cellNum > grid_Cells){ + LogError( + logfp, LOGFATAL, + "%s: cell number (id=%d) is larger than number of cells in grid (n=%d).", + grid_files[GRID_FILE_SOILS], cellNum, grid_Cells + ); } + /* If the user specified a cell to copy we will perform the copy, regardless of whether or not they also entered parameters. */ if(entriesRead == 1){ entriesRead = sscanf(buf, "%d,%d", &cellNum, &cellToCopy); + + if(cellToCopy > grid_Cells){ + LogError( + logfp, LOGFATAL, + "%s: cell to copy (id=%d) not present in grid (n=%d).", + grid_files[GRID_FILE_SOILS], cellToCopy, grid_Cells + ); + } + if(entriesRead == 2){ return cellToCopy; } else { @@ -1041,6 +1055,14 @@ static int _read_soil_line(char* buf, SoilType* destination, int layer){ } if(entriesRead == 16) { + if(layerRead > destination->num_layers){ + LogError( + logfp, LOGFATAL, + "%s: cell %d has too many soil layers (%d for max=%d).", + grid_files[GRID_FILE_SOILS], cellNum, layerRead, destination->num_layers + ); + } + return SOIL_READ_SUCCESS; } else { return SOIL_READ_FAILURE;