0

So my code for pset2 Substitution works about 99% correctly. When I ran check50, I realized that there is still an issue if the user does not type the key right after the program name at the command line.

I THOUGHT I addressed this with the code below, but it does not seem to work. Instead of showing my error message and returning 1, I get Segmentation fault (core dumped).

Does anyone know why? Any suggestions for a fix?

Here's the code I thought would require the user to input a string after the program name:

if (argc != 2)
{
    printf("Usage: ./substitution key\n");

    return 1;
}

enter image description here

1 Answer 1

0

It's a syntax error. The correct operator is !=, with only one equals sign. That will fix the compiler error.

And as soon as it compiles, you'll find the next bug - the code fails when there's no parameter given, by generating a seg fault. That's a sequencing problem.

The problem is that the code tries to do something with argv[1] before it checks argc.

If argc=1, then argv[1] doesn't exist, so any attempt to do something with argv[1] will generate a seg fault. The code MUST check argc first.

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

p.s. In the future, instead of images, please cut and paste code into questions so it can be readily read, and copied for testing. Also, please put the commentary into the question and not into the code. It makes it a lot easier to respond to questions. ;-)

4
  • This was super helpful! Thank you! Nov 15, 2022 at 11:44
  • And I will do that... I've had trouble with some of the code that I try to paste into the questions here using the {} code button not being included for some reason... Maybe it's the comments? Nov 15, 2022 at 11:46
  • Just highlight ALL the code at once and click on the curly braces.
    – Cliff B
    Nov 15, 2022 at 23:24
  • Ah got it. Thank you. Nov 18, 2022 at 12:08

You must log in to answer this question.

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