Skip to content

Commit 2ebcd1f

Browse files
committed
Fix: eliminate buffer overflow in countFields() and add callers error handling
1 parent 736e91e commit 2ebcd1f

File tree

3 files changed

+215
-52
lines changed

3 files changed

+215
-52
lines changed

src/common/modelParams.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ void checkAllRead(ModelParams *ModelParams) {
4545
if (!param->isRead) {
4646
if (param->isRequired) { // should have been read but wasn't!
4747
okay = 0;
48-
logError("Did not find read required parameter %s\n", param->name);
48+
logError("Did not find required parameter %s\n", param->name);
4949
} else {
5050
missingOptParam = 1;
5151
}
@@ -127,6 +127,10 @@ void initializeOneModelParam(ModelParams *modelParams, char *name,
127127

128128
void checkParamFormat(char *line, const char *sep) {
129129
int numParams = countFields(line, sep);
130+
if (numParams == -1) {
131+
logError("memory allocation failure in parameter file processing\n");
132+
exit(EXIT_CODE_INTERNAL_ERROR);
133+
}
130134
if (numParams > 2) {
131135
logWarning("extra columns in .param file are being ignored (found %d "
132136
"columns)\n",

src/common/util.c

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,19 @@ int stripComment(char *line, const char *commentChars) {
5050
// count number of fields in a string separated by delimiter 'sep'
5151
int countFields(const char *line, const char *sep) {
5252
// strtok modifies string, so we need a copy
53-
char lineCopy[256];
53+
size_t lineLen = strlen(line);
54+
char *lineCopy = (char *)malloc(lineLen + 1);
55+
if (lineCopy == NULL) {
56+
return -1; // Handle allocation failure
57+
}
5458
strcpy(lineCopy, line);
59+
5560
int numParams = 0;
5661
char *par = strtok(lineCopy, sep);
5762
while (par != NULL) {
5863
++numParams;
5964
par = strtok(NULL, sep);
6065
}
66+
free(lineCopy);
6167
return numParams;
6268
}

0 commit comments

Comments
 (0)