I have a snippet of code, in C for reading entries from a passwd-style database:
do {
if (fscanf(db, "%s:%s:%d", uname, passwd, &gid) == EOF) {
return NULL;
}
} while (strcmp(uname, username));
However, when running it, it gives a segmentation fault. After running it in the debugger, I found that the strcmp
part is the part raising the segfault. Data types:
db
is FILE *
, opened already.uname
and passwd
are char *
, both initialised to NULLusername
is char [64]
gid
is int
How can I fix this problem, and alternatively how can I parse the database without needing to use this ugly hack?
If both the string variables uname
and passwd
are just pointers, that doesn't point anywhere, what do you think happens when fscanf
tries to use those pointers and write the string into memory?
That will lead to undefined behavior, as will the dereferencing done in the strcmp
call.
You should use arrays for the uname
and passwd
variables as well.