-2

segmentation problem occur while debugging the code how can i resolve the issue

debugging problem can't find a solution please help

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

 int main(int argc,string argv[])
 {

    int len = strlen(argv[1]);

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


 }

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Rufus
  • 1
  • 1
  • 3
    Look at your code and ask yourself when is the proper time to check `argc`, which dictates the valid index range of `argv` : Is it before, or after, you use `argv` in that `strlen` call ? Maybe refer to your C reference and/or [read this](https://stackoverflow.com/questions/3898021/regarding-mainint-argc-char-argv). – WhozCraig Jan 30 '23 at 03:46
  • [Please don't post screenshots of text/data/code/errors](https://meta.stackoverflow.com/a/285557/15405732). They can't be searched or copied, or even consumed by users of adaptive technologies like screen readers. Instead, paste the code as text directly into your question/answer. If you select it and click the {} button or Ctrl+K the code block will be indented by four spaces, which will cause it to be rendered as code. Please edit your question to turn the image into well-formatted text. – Koedlt Feb 02 '23 at 09:03

1 Answers1

2

Check if argv is valid before accessing it:

int len = strlen(argv[1]);

    if(argc != 2 )

If argc != 2 evaluates to true, then argv[1] would be a NULL pointer (assuming argc is 1).

Check if the arguments are valid before you try to access them, else your program could dereference a NULL pointer and exhibit undefined behaviour.

if (argc != 2) {
   /* print usage message here.. */
   return EXIT_FAILURE;
}

strlen() returns a size_t:

Note that strlen() returns a size_t, not an int. Do not mismatch numeric types.

Error messages should go to stderr:

Error messages deserve to be printed to stderr, not stdout.

fprintf(stderr, "Usage:./substitution\n

Or as formatted output is not required here, simply:

fputs ("Usage:./substitution\n", stderr);

See also: Why use stderr when printf works fine?

Harith
  • 4,663
  • 1
  • 5
  • 20