0

So I'm having issues with the hail caesar section of problem set 2. My code compiles, but when I run it, I receive 'segmentation default.' Any ideas on where the errors are? I would really appreciate any advice :) Thanks in advance!

My code:

int main(int argc, string argv[])
{
if (argc != 2)
    {
        printf("Please enter 2 arguments only\n");
        return 1;
    }

if ((isdigit(argv[1]) == 0) || (isdigit(argv[1]) && argv[1] < 0))
    {
        printf("Please provide a non-negative integer\n");
        return 1;
    }


if ((argc == 2) && ((isdigit(argv[1]) && argv[1] > 0)))
    {
        string key = argv[1];
        int k = atoi(key);

        printf("What is your message? \n");
        string message = GetString();  
        printf("\n");
        int n = strlen(message);

    for (int i = 0; i < n; i++)
        {
            if (isalpha(message[i]))
                {
                    if (islower(message[i]))
                        {
                            int crypt = ((message[i] + k) % 26);
                            printf("%c", crypt);
                        }
                    if (isupper(message[i]))
                        {
                        int cryptic = ((message[i] + k) % 26);
                        printf("%c", cryptic);            
                        }
                }

            else
                {
                printf("%c", message[i]);
                }
        }   
    return 0; 
    }
0
0

Wow, deja vu. Just saw this for a pset4 question. The problem lies early in your code:

if ((isdigit(argv[1]) == 0) || (isdigit(argv[1]) && argv[1] < 0))

The isdigit() function is designed to check whether a single character is a digit, not a string. This code is trying to shove a string down it's throat, so it chokes and coughs up a seg fault. You might want to say that it's only getting a single digit, but that's not exactly true. A string of a single digit will also include the end of string marker.

As a side note, think about this line:

if ((argc == 2) && ((isdigit(argv[1]) && argv[1] > 0)))

Earlier, you check whether argc !=2. If not, it exits the program. So why do you need to check this again? At this point, argc must be 2.

Next, say that the parameter given for argv[1] is "3". Remember, all argv arguments are strings. argv[1] > 0 won't work as intended. I'll just say that atoi() is your friend.

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

1
  • Thanks Cliff B! I was over-complicating my conditions. I fixed my code and no longer get segmentation default when running it :) The encryption section is having issues...but that is a different issue. Oct 20 '16 at 2:09

You must log in to answer this question.

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