【问题标题】:Segmentation fault (core dumped) Error - C Language分段错误(核心转储)错误 - C 语言
【发布时间】:2021-03-21 16:57:44
【问题描述】:

我有以下代码。我希望使用命令行参数来访问程序或提供错误消息。尽管在 if(argc > 2) 我收到“分段错误(核心转储)”错误,但一切都给出了正确的错误消息。我在这里找不到错误。我做了一些研究,错误是当我访问我不应该访问的内存时。有人在下面的代码中看到是什么原因造成的吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){

   int a;
   if(argc > 2){
      printf("Please enter a command");
   }
   a = atoi(argv[1]);

   if(a < 40 || a > 90){
      printf("Price must be from 40 to 90 .\n");
   }
   if(a % 5 != 0){
      printf("Price must be a multiple of 5.\n");
   }
   if(a > 40 || a < 90){
      printf("Welcome!\n");

   }

}

【问题讨论】:

  • 你传递了什么参数? argv[1] 仅在 argc2 或更多时有效。如果 (argc == 1` (你没有检查),那么它的访问越界了。
  • 条件a &gt; 40 || a &lt; 90 将永远为真。

标签: c


【解决方案1】:

这可能是因为您的代码在检查了错误情况后仍在继续执行后续步骤。当您的参数少于 2 个时,您的代码将打印错误以输入命令,但将继续下一步访问无效的 argv[1](因为您没有第二个参数)。所以你在这里得到了分段错误。

【讨论】:

    【解决方案2】:

    您进行了检查,但无条件执行了其余代码。

    当传递的参数不够时停止执行。

    你的情况也是错误的。条件应该是“小于”,而不是“大于”。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int main(int argc, char *argv[]){
    
       int a;
       if(argc < 2){ /* use correct condition */
          printf("Please enter a command");
          return 1; /* stop execution */
       }
       a = atoi(argv[1]);
    
       if(a < 40 || a > 90){
          printf("Price must be from 40 to 90 .\n");
       }
       if(a % 5 != 0){
          printf("Price must be a multiple of 5.\n");
       }
       if(a > 40 || a < 90){
          printf("Welcome!\n");
    
       }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2017-02-25
      • 2016-07-12
      • 2018-03-16
      相关资源
      最近更新 更多