I've looked at other similar issues on the site but I still don't see what I'm missing. C is a new and terrifying beast for me, so I'm sure it's something simple, but I'm getting segmentation fault(core dump) when the code reaches the fgets();
line just inside the while loop.
I tried writing a string directly to currentInput
instead and still get it, so I think I'm somehow accessing the string wrong?
My understanding is that a segmentation fault is caused by accessing memory that (the program?) doesn't have access to...
As an aside, is there a way to use a string literal in strcmp(); so I can just compare to "END"?
void runCommands()
{
char * currentInput = (char*)malloc(100); //100 char input buffer
char * cmd = (char*) malloc(CMD_LENGTH);
char * target = (char*) malloc(UID_LENGTH);
char * key = (char*) malloc(KEY_LENGTH);
char * endstr = "END";
cmd = "UNDEF";
target = "UNDEF";
key = "UNDEF";
ushort tokens;
while (strcmp(cmd, endstr) != 0) //Run until command is "END"
{
printf("ENTER INSTRUCTION: ");
fgets(currentInput, sizeof(currentInput), stdin); //FAULT OCCURS HERE
tokens = sscanf(currentInput, "%[^,\n],%[^,\n],%s", cmd, target, key); //parse string for values
if (tokens <= 3 && tokens >= 1) //ensure valid # of tokens passed
{
fprintf(stdout, "TOKENS:\nCMD: %s\ntarget: %s\nkey: %s\n", cmd, target, key);
switch (tokens)
//restore UNDEF for non-existent tokens
{
case 1:
target = "UNDEF";
/* no break */
case 2: //intentional fallthrough
key = "UNDEF";
break;
default:
break;
}
/* handle commands */
if (strcmp(cmd, endstr) == 0)
{
end(keyfile);
} //write file and exit function
else if (strcmp(cmd, "DELETE") == 0)
{
delete(target, key);
} //delete specified key from UID
else if (strcmp(cmd, "VALIDATE") == 0)
{
validate(target, key);
} //valid/not valid based on key presence
else if (strcmp(cmd, "ADD") == 0)
{
add(target, key);
} //add key to target UID
else if (strcmp(cmd, "PRINT") == 0)
{
print(target);
} //print sorted keys for UID or all keys for ALL
else
{
invalidCMD(cmd);
} //error message for invalid command
}
else
{
invalidCMD(currentInput); //use whole input as bad command if invalid format
}
}
free(currentInput);
free(target);
free(key);
free(cmd);
}