【发布时间】:2018-03-13 02:59:14
【问题描述】:
int main (int argc, char* argv[]){
int toSleep;
int produce;
int consume;
int i = 0;
//get the values for sleep, produce, consume
toSleep = atoi(argv[1]);
produce = atoi(argv[2]);
consume = atoi(argv[3]);
//check if the user input a vaild inpusts
//if(argc !=4){
//printf("You are missing an input\n");
// exit(0);
//}`enter code here`
if(toSleep == '\0' || produce == '\0' || consume == '\0' ){
printf("You are missing an input\n");
exit(0);
}else if (toSleep <=0 || produce<= 0 || consume <=0 ){
printf("Please provide a vaild inputs \n");
exit(0);
}else {
//continue to the program
}
我正在努力确保用户将准确输入 3 个输入;如果缺少或为空,我应该打印一条错误消息并终止程序。当我尝试编译它时,我总是得到这个错误
./a4 makefile:5: recipe for target 'semaphore' failed make: *** [semaphore] Segmentation fault (core dumped)
谁能告诉我我在这里做错了什么?
【问题讨论】:
-
您注释掉了使用
argc的if,但这就是您如何验证确切的三个参数。是您尝试编译还是尝试运行程序时出现的错误? -
请注意,如果您将
NULL传递给atoi(),则会发生未定义的行为。所以检查为时已晚,而且'\0'只是0的花哨符号,表示您打算与字符串中的 null 字符进行比较,但这并不意味着atoi()的论点是NULL。你想要的很简单,我真的很惊讶你问,谷歌上去。 -
我对示例下的段落感到困惑。什么是“信号量”?这是这个程序编译成的名字吗?如果包含 makefile、用于运行它的命令行以及它产生的输出(格式良好),您可能会获得更多帮助
-
我做了评论部分,但仍然给我同样的错误。另外,如果用户输入的项目少于或多于 3 个,它是否会起作用。
-
您确实应该在问题中添加格式化版本的 Makefile。如果我猜对了如何格式化,
semaphore是一个没有先决条件的 Makefile 目标,其配方只是运行a4...没有参数...所以程序当然会崩溃...您的索引超出了 argv 的范围。
标签: c