gpt4 book ai didi

c - 神奇的段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:07 25 4
gpt4 key购买 nike

我查看了网站上的其他类似问题,但我仍然看不出我遗漏了什么。 C 对我来说是一个新的可怕的野兽,所以我确信它很简单,但是当代码到达while 循环。

我尝试将一个字符串直接写入 currentInput 而仍然得到它,所以我认为我以某种方式访问​​了该字符串错误?

我的理解是,段错误是由访问(程序?)无法访问的内存引起的...

顺便说一句,有没有办法在 strcmp(); 中使用字符串文字?所以我可以比较“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);
}

最佳答案

您通过覆盖 malloc 返回的指针值导致内存泄漏和未定义的行为:

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);
//...
// This is where you cause the issue
char * endstr = "END";
cmd = "UNDEF";
target = "UNDEF";
key = "UNDEF";

由于您切断了代码,我无法评论您的其余代码以确定还有什么会导致问题。

一件事是您肯定没有正确使用 sizeof(),因为 sizeof(currentInput) 等于 sizeof(char*),而不是字符串的长度。

关于c - 神奇的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28334377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com