0

Check if the user provides no command-line arguments, or more, it prints Usage: ./caesar key. If the command-line argument is one then it checks if all the characters in the string are digits. If I enter ./caesar in the command line, I get a segmentation fault error. This doesn't happen when the IF is before WHILE. I am not sure as to why this error occurs. Really appreciate any help!

   #include <stdio.h>
   #include<stdlib.h>
   #include<string.h>
   #include<ctype.h>
   #include<cs50.h>

   int main(int argc, char*argv[])
   {
    string str = argv[1];
    
  //check if argv[1] are all digits
    while(argc == 2)
    {
      for(int i = 0; i< strlen(str); i++)
       {
          if(!isdigit(str[i]))
          {
             printf("Usage: ./caesar key \n");
             break;
          }
       }
        break;
    }
    
   // check if argument count is not 2
   if(argc != 2)
    {
       printf("Usage: ./caesar key \n");
    }
   
   return 0;

   }
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Annie
  • 21
  • 2
  • 10
  • 4
    `if(argc != 2)` should be the first thing in your program, before `string str = argv[1];` and you should just return if it's wrong. Once you've done that `while(argc == 2)` is unnecessary because you've already checked and it's not going to change unless you change it yourself. – Retired Ninja Jul 24 '21 at 04:02
  • Sidenote: Don't abuse `while(...) { ....; break;}` as `if` statement. This is not the obfuscated c code contest. The `if` statement exists for a reason. – HAL9000 Jul 24 '21 at 16:06
  • I got to know why my code went wrong. If my command-line argument was ./caesar then argc = 1 and argv[0] = ./caesar but the compiler has no idea what argcv[1] is since my argument count is one and initializing argv[1] to a string is what gives a segmentation error (where I was trying to access memory that didn't exist). Thanks guys for reaching out! – Annie Jul 26 '21 at 03:03

1 Answers1

0

./casear is argv[0] meaning string str = argv[1]; is null resulting in a seg fault.

purple
  • 212
  • 1
  • 8
  • The former was the cause because of accessing a null pointer, if that part is corrected the program executes without erros. – Annie Jul 26 '21 at 03:37