I am facing a small problem while solving caesar (PSET2).

I can make caesar but when I execute the program and provide a numerical command-line argument, I get back: Segmentation Fault, and the program just stops.

I would be extremely obliged if you could help me figure where the problem lies.

Any other feedback shall also be highly appreciated!

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

int main(int argc, string k [])
   if ( isalnum(k [1]) || argc == 2)
       string s = get_string (" Message");
       for (int i = 0, n = strlen(s); i < n; i++)
          if (isalpha(s[i]))
              int K = atoi ( k[1] );
              int p = atoi ( s );
              int c = (p + K) % 26;
              int a = c + p;
              printf ("%c", a + p);
              return 0;


       printf("Usage: ./caesar key \n");
       return 1;

The immediate problem lies here:

if ( isalnum(k [1]) || argc == 2)

The isalnum() function requires a single char to be passed to it. k[1] is a string. Pass a string to isalnum or any of it's cousins and you get a seg fault.

The next issue is in the same line of code. ALWAYS check the value of argc FIRST. If argc is too small, it means that there aren't enough arguments. If there aren't enough arguments and the code tries to access one, it will throw a seg fault (different than your current one) because the code is trying to access a nonexistent var. If the argc test comes first and it fails, it doesn't matter what is tested next because the overall if statement is resolved and further tests won't be executed. Reverse them, and you can get a seg fault.

Programming note: The standard for the main() signature is this:

int main(argc, argv[])

It should always look like this, never using any other var names, like k[]. You need to break that habit immediately.

There may be more issues, but I'll let you find out if there are - giving you a chance to work on them. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

  • Ah... Now I get what I was doing wrong! Thank you so very much for your help! :-) – Hamster1303 Oct 13 '20 at 6:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .