user15264532
user15264532

Reputation:

How to solve segmentation fault in c?

When I was making my program I got an error type of thing called Segmentation Fault.

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

int main(int argc, string argv[])
{
    char i = strlen(argv[2]);
    if (argc == 2)
    {
        printf("%i %s %hhd", argc, argv[2], i);
    }
}

I run this program using these commands

make substitution

and then

./substitution abcdefghijklmnopqrstuvwxyz

In this we have to add a 26 word key which in the above line is a to z.

Please help if you know to solve

Upvotes: 0

Views: 239

Answers (2)

Rohan Bari
Rohan Bari

Reputation: 7726

You got hit with segfault because the number of required arguments specified was done poorly. The main problem is here:

if (argc == 2)

The number of actual arguments passed by the user is equal to the number of required arguments minus 11. It should be:

int main(int argc, char *argv[]) {
  if (argc != 3) {
    // Number of arguments are either greater or lesser than 3
    // Handle the error
  }

  // Ok...
}

You can safely use the arguments now.


1. The calling command for the program, for example ./a.out is also counted as an argument (argv[0]).

Upvotes: 0

William Pursell
William Pursell

Reputation: 212484

If you invoke your program with:

./substitution abcdefghijklmnopqrstuvwxyz

argc will be 2, and argv will be an array of 3 pointers:

argv[0] points to the string ./substitution, argv[1] points to the string abcdefghijklmnopqrstuvwxyz, and argv[2] is NULL. If you attempt to compute the length of NULL by calling strlen(argv[2]), that is an error. You must not pass NULL to strlen. I think your error is simply mis-indexing the argv array. Arrays in C are zero based. If you want to compute the length of the first argument, you want to work with argv[1], not argv[2]:

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

int
main(int argc, char *argv[])
{
    int rc = EXIT_FAILURE;
    if( argc > 1 ){
        size_t i = strlen(argv[1]);
        printf("%i %s %zd\n", argc, argv[1], i);
        rc = EXIT_SUCCESS;
    }
    return rc;
}

Upvotes: 1

Related Questions