0

I can't figure out why i'm getting a segmentation fault. As far as I understand if there is other than argc = 2 the program should simply print the right usage and return 1. What can be causing this?

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


 int main(int argc, string argv[])
{
    int k = atoi(argv[1]);

    if (argc != 2)
    {
        printf("Usage: ./caesar <argument>\n");
        return 1;
    }
    else
    {
        //get message from user
        string m = GetString();

        for (int i = 0, n = strlen(m); i < n; i++)
        {
            if (islower(m[i]))
            { 
                //wrap a-z 
                int letterlow = (((m[i] + k) - 97) % 26) + 97;
                printf("%c", letterlow);    
            }
            else if (isupper(m[i]))
            {
                int letterupp = (((m[i] + k) - 65) % 26) + 65;
                printf("%c", letterupp);
            }
            else
            {
                printf("%c", m[i]);
            }
        }
    }
    printf("\n");
    return 0;
}
1
  • If I run the program with no arguments i get the segfault. When I run check50 I get ":( handles lack of argv[1] \ expected output, not standard error of "/opt/sandbox50/bin/run.sh: line 31: 160..."" – Miguel Saitz Jul 31 '16 at 13:05
3
int k = atoi(argv[1]);
if (argc != 2)
{...........

You are assuming that argv [1] exists before checking that really exists, if we have more than two arguments your program will work well, but if you have only one argument are accessing a memory area to which you should not access and argv [1] "does not exist" hence your segmentation fault

Si esto responda a su pregunta, por favor haga clic en la marca de verificación para aceptar!!!

You must log in to answer this question.

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