looking for a way to read arguments from a configuration file I found a nice way to do it but the thing is that something really weird happens when I try to count the lines.
This is the code:
FILE *file = fopen("config", "r");
char line[100];
int linenum = 0;
//int foo; Uncomment and it starts to working, doesn't matter if you rename it.
while(fgets(line, sizeof(line), file) != NULL) {
char option[4];
char arg[100];
if (line[linenum] == '#')
continue;
linenum++;
if (sscanf(line, "%s %s", option, arg) != 2)
fprintf(stderr, "Syntax error, line %i\n", linenum);
The config file looks like this:
#config file
option1
option2
option3
So the result is:
Syntax error, line 1
Syntax error, line 0
Syntax error, line 0
But if I declare an int variable with any name before while loop it starts to working!
The result is:
Syntax error, line 1
Syntax error, line 2
Syntax error, line 3
What in the world is happening here? my mind is gonna blow, maybe it’s something dumb but I don’t see any reason for this.
Any time you see strange behavior like this, you should start looking for memory overrun errors. Typical symptoms include:
In this case, as the other answers point out, you have two potential memory-related errors:
The line
if (line[linenum] == '#') continue;should be
if (line[0] == '#') continue;Otherwise the index will be invalid when
linenum > 99.And the line
if (sscanf(line, "%s %s", option, arg) != 2){will overrun the
optionandargvariables if the input strings are too long. (The error you’re seeing occurs because the text (e.g.option1) is longer than 4 characters and overflowsoption. You can fix this in several ways:option. You’ll need to know the maximum length of the input strings in order to choose an appropriate size.option:if (sscanf(line, "%3s %99s", option, arg) != 2){This may cause unexpected output for long input strings, because
argwill contain the remainder of the string inoptionif it’s truncated.amodifier to tellsscanfto allocate memory for the strings as it reads them:char **str1, **str2;if (sscanf(line, "%as %as", &str1, &str2) != 2){