int main(){
char *input = NULL;
char *line[2048];
size_t inputChars = 0;
size_t bufferSize = 0;
char *command = NULL;
char *arguments[2048];
printf(":");
fflush(stdout);
while((inputChars = getline(&input , &bufferSize , stdin)) > 0){
memset(line, '\0' , (sizeof *line * sizeof line[0]) );
memset(arguments, '\0' , (sizeof *arguments * sizeof arguments[0]));
if(inputChars == -1){
clearerr(stdin);
}
else{
parseLine(input,line);
command = line[0];
int i = 0;
int j = 1;
while(line[j] != NULL)
{
arguments[i] = line[j];
i++;
j++;
}
if((*line[0] != '#') && (*line[0] != '\n'))
{
runCommand(command,arguments);
}
printf(":");
fflush(stdout);
}
input = NULL;
}
}
int isBackground(char* args[])
{
int i = 0;
int pos = 0;
while (args[i] != NULL)
{
pos++;
i++;
}
if (*args[pos - 1] == '&')
{
background++;
return true;
}
else return false;
}
void runCommand(char* cmd, char* args[])
{
printCommandLine(cmd, args);
if (isBackground(args))
{
printf("Background Processes: %i\n",background);
}
}
void printCommandLine(char* cmd, char* args[])
{
printf("Command: %s\n",cmd);
printf("Arguments:\n");
int i = 0;
while (args[i] != NULL)
{
printf("%s\n",args[i]);
i++;
}
}
Valigrind 结果:
xcode 输出:
我找不到哪里出错了。我正在为可以接受带有参数列表的命令的命令行编写一些简单的代码。该程序对于长度 <= 7 的字符串数组运行良好,并且在第一次输入此大小的命令后适用于每个命令数组。我不知道我在哪里使用未初始化的值。当代码中断时,我在遍历参数数组时无法访问。我怀疑这可能与填充参数数组的 main 中的 while 循环有关,但我可能错了。真的坚持这一点。感谢您的帮助或建议,如果您有任何想法。
最佳答案
memset(arguments, '\0' , (sizeof *arguments * sizeof arguments[0]))
这是您的代码导致未初始化值的问题。
*arguments
与 arguments[0]
相同。 sizeof
都是 sizeof(char*)
。
这意味着您只初始化缓冲区中的几个条目。
你需要
memset(arguments, '\0', sizeof(arguments));
上一行也是如此
memset(line, '\0', sizeof(line));
关于c - 未初始化的值是由堆栈分配创建的 - 无法找到我出错的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45497380/