0

I'm trying to work on "substitution" problem set, but I'm getting an error of "Segmentation Fault" when I run the program below:

In this part of the program I just want to check if the keyword has 26 letters and if it is alphabetical.

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

int main(int argc, string argv[])
{
    printf("%s\n", argv[0]);
    printf("%s\n", argv[1]);
    
    string keyword = argv[1];
    int key_length = strlen(keyword);
 
    if (key_length != 26 || isalpha(argv[1]))
    {
        printf("INVALID\n");
    }
    else
    {
        printf("VALID\n");
    }
}

Although I get Segmentation Fault when I run this program with: ./substitution JTREKYAVOGDXPSNCUIZLFBMWHQ, when I run with debug50 (debug50 substitution JTREKYAVOGDXPSNCUIZLFBMWHQ) I don't get any error messages and the program runs completely normal.

Can anyone help me with this problem?

Thanks in advance,

1

The documentation for isalpha explains that the input should be an unsigned char. https://manual.cs50.io/3/isalpha By passing in a string instead of a single char, the underlying library code is misbehaving. Too bad it's not a compile error.
Why debug50 behaves differently, there's probably different library code being executed. Many advanced things happen "under-the-hood" which aren't taught as part of this class.

1
  • Thank you so much for the answer!! It helped me solve the problem. Mar 16 at 3:00
1

The problem lies here:

if (key_length != 26 || isalpha(argv[1]))

The isalpha() function and all of it's cousin issomething() functions take a single char as input. If you try to give it a string (argv(1) is a string, not a char, even if it only has one char), it causes a seg fault. It's that simple.

As for debug50, it is a wrapper around gdb. Think of it like training wheels for gdb. Having said that, all debuggers have the nasty habit of masking some errors. Seg faults are at the top of that list.

Although this question was answered and the answer accepted, I wanted to make clear exactly where the problem is and why it happens.

1
  • Thank you Cliff! It was really helpful. Mar 16 at 12:13

You must log in to answer this question.

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