My problem is this:
#define MAX_LINE_LENGTH 100
#define MAX_RESOURCES_NUM 150
#define MAX_REQUESTS_NUM 150
#define MAX_REPAIRS_NUM 150
struct resource {
long ID;
char* name;
long qty;
sem_t freeResources;
};
struct request {
long licensenum;
long time;
long repcount;
long *repIDarr;
};
struct repair {
long ID;
char* name;
long hours;
long rescount;
long *resIDarr;
};
struct resource* resarr[MAX_RESOURCES_NUM];
struct request* reqarr[MAX_REQUESTS_NUM];
struct repair* reparr[MAX_REPAIRS_NUM];
int timevar, threadcount;
//Func declarations
int main(int argc, char* argv[]){
FILE *resfile, *reqfile, *repfile;
char line[MAX_LINE_LENGTH], *refer;
int i = 0;
timevar = 0;
threadcount=0;
if(argc < 4) {
printf("Not enough arguments!");
return 0;
}
if((resfile = fopen(argv[1], "r")) == NULL || (repfile = fopen(argv[2], "r")) == NULL || (reqfile = fopen(argv[3], "r")) == NULL){
perror("Open file failed");
return 0;
}
//Initialize resources
while(fgets(line, 100, resfile) != NULL){
char* token;
refer = line;
token = strsep(&refer, "t");
long ID = atoi(token);
char* name = strsep(&refer, "t");
token = strsep(&refer, "t");
if(token = NULL){
printf("Xn");
return 0;
}
long qty = atol(token);
}
fclose(resfile);
fclose(reqfile);
fclose(repfile);
return 0;
}
This is only part of the code, that is enough to reproduce the problem with.
I have a txt file called resources.txt:
13 car lift 8
17 front alignment 2
03 headlights adjust 2
10 oil drain 4
23 computerized check 2
35 pneumatic drive 4
40 ceiling winch 2
99 John Smith 1
29 air compressor 1
66 flats tub 1
88 paint gun 1
I separate any line with strsep()
by TAB
.
The problem is that I get a Segmentation fault as soon as I run the program.
When I delete this line:
long qty = atol(token);
at the end of main, I don’t get the error.
I can’t find what causes it.
The strangest thing is that when I run the program on my personal computer it runs fine (on CentOS)
but when I run it in my college computers (with the same CentOS) it shows me the error.
Any ideas?
2
Answers
So I pigured out what caused the problem. I found out that
fgets
didn't returnEOF
when I thought it would, because it catches 'n
' beforeEOF
, so I ended up handling a string 'n
' like it was a true line of information what causedstrtol
get aNULL
pointer, which caused a Segmentation Fault error. The fix was relatively easy; I had to prevent from this while loop:to iterate when 'line' points at a string that has only 'n', so I added a condition to the while loop:
And now it's perfect.
does not what you expect.
Change it to be
And to not step into this “stupid” 😉 trap again, you might like to consider using “Yoda-Conditions” from now on, that is putting the “constant” to the left, like so:
Because if you would have done
the compiler would have complained massively.
And, BTW, if you’d have traced the code using a single-step debugger, you mostly likely would have notice this bug very soon.