Thread: Segmentation fault - getopt_long()

  1. #1
    Registered User
    Join Date
    Oct 2014
    Posts
    3

    Question Segmentation fault - getopt_long()

    Hello friends

    I am trying to implement command line options in a C Program. Please refer to the code below.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <string.h>
    #include <getopt.h>
    
    struct option longopts[] = {
        {"help",  no_argument, 0, 'h'},
        {"open",  required_argument, 0, 'o'}
    };
    
    void usage(FILE *file);
    
    int main (int argc, char * argv[]) {
    
        int i, ch, indexptr = 0;
        opterr = 0;
    
        while ((ch = getopt_long(argc, argv, "ho:", longopts, &indexptr)) != -1) {
            switch(ch) {
                case 'h':
                    usage(stdout);
                    exit(0);
                    break;
                case 'o':
                    printf("Optarg file will be opened here\n");
                    break;
                default:
                    printf("Didn't recognize that option. Try again\n");
                    exit(0);
            }
        }
    
        argc -= optind;
        argv += optind;
    
        if(argc == 0){
            fprintf(stderr,"ERROR: Required arguments missing. Please refer to the usage below: \n");
            usage(stderr);
            exit(1);
        }
    
        return 0;
    }
    
    void usage(FILE *file) {
      if(file == NULL){
        file = stdout;
      }
    
      fprintf(file,
              "./program [OPTIONS] file.txt\n"
              "  --help        \t Print this help screen\n"
              "  --open        \t Open a file\n");
    }
    When I compile it and run,
    for
    Code:
    ./program --help
    it's not generating any errors.

    But for
    Code:
    ./program --he
    it's generating Segmentation fault. It is throwing up this error for --h, --he, --hel etc.,

    Also, when I give, --open as the option, it's not even recognizing this.

    I took a look at the manual of getopts_long but couldn't identify the problem.

    Can somebody point out the mistake?

    Thanks in advance.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    This is not a C problem. getopt_long() is linux specific. Try asking your question in a linux programming forum.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    *moved to Linux programming*
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    O_o

    You must correctly use the `getopt_long' interface.

    Specifically, you aren't providing a valid `longopts' pointer.

    You should read some more examples.

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    It all looks fine here.
    Code:
    $ gcc -g bar.c
    $ ./a.out --hel
    ./program [OPTIONS] file.txt
      --help                 Print this help screen
      --open                 Open a file
    $ ./a.out --he
    ./program [OPTIONS] file.txt
      --help                 Print this help screen
      --open                 Open a file
    $ ./a.out -h
    ./program [OPTIONS] file.txt
      --help                 Print this help screen
      --open                 Open a file
    I used -g to add symbols to the executable, in the expectation of having to use gdb.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Oct 2014
    Posts
    3
    Hi Salem

    Thanks for your input.

    Did you try ./a.out -o or ./a.out --open?


    Quote Originally Posted by Salem View Post
    It all looks fine here.
    Code:
    $ gcc -g bar.c
    $ ./a.out --hel
    ./program [OPTIONS] file.txt
      --help                 Print this help screen
      --open                 Open a file
    $ ./a.out --he
    ./program [OPTIONS] file.txt
      --help                 Print this help screen
      --open                 Open a file
    $ ./a.out -h
    ./program [OPTIONS] file.txt
      --help                 Print this help screen
      --open                 Open a file
    I used -g to add symbols to the executable, in the expectation of having to use gdb.

  7. #7
    Registered User
    Join Date
    Oct 2014
    Posts
    3
    Hi Soma

    Can you point me to some good examples?

    I've been searching and reading things, but I don't feel they are complete.

    Apologies if I'm missing something.

    Thanks
    Quote Originally Posted by phantomotap View Post
    O_o

    You must correctly use the `getopt_long' interface.

    Specifically, you aren't providing a valid `longopts' pointer.

    You should read some more examples.

    Soma

  8. #8
    Ticked and off
    Join Date
    Oct 2011
    Location
    La-la land
    Posts
    1,728
    Quote Originally Posted by grumpy View Post
    getopt_long() is linux specific.
    No, it was originally a GNU C library extension, but nowadays implemented on BSDs, including e.g. Macs.

    It's a pity there is no GNU or POSIX C or "non-Windows" forum, since questions pertaining to those are so readily shunted to the "Linux programming" sub-forum, while Linux is just one environment those are available. (Might be one reason why there are so few non-Windows, non-Linux programmers here, just an occasional microcontroller person.)

    Quote Originally Posted by capslocktrojan View Post
    Code:
    struct option longopts[] = {
        {"help",  no_argument, 0, 'h'},
        {"open",  required_argument, 0, 'o'}
    };
    The array of options should end with a terminating entry (typically, NULL or all zeroes). Without it, getopt_long() will try to access past the end of the array.

    (Some functions take both a pointer and a length; those arrays do not need a terminator entry. Other functions, like getopt_long(), take just the array (or the pointer to the first entry in the array); that's a clear indicator you do need the terminating entry.)

    Salem used a different compiler or compiler options, that happens to generate a long enough run of zeros after that array -- just as if you had added the terminating entry.

    In other words:
    Code:
    struct option longopts[] = {
        {"help",  no_argument, 0, 'h'},
        {"open",  required_argument, 0, 'o'},
        {0}
    };
    A good example is available at the Linux man-pages project, getopt_long(3) man page, near the bottom of the page. (The project name refers to man pages that are relevant to all Linux applications, not man pages defined by Linux folks.) Each page has a Conforming to section you can check to see when and where the function is available.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In GDB no segmentation fault but while running segmentation fault
    By Tamim Ad Dari in forum C++ Programming
    Replies: 2
    Last Post: 12-10-2013, 11:16 AM
  2. Segmentation fault, how come?
    By Fader_Berg in forum C Programming
    Replies: 18
    Last Post: 08-31-2010, 01:58 AM
  3. Odd Segmentation Fault
    By JohnnyAppleseed in forum C Programming
    Replies: 7
    Last Post: 08-24-2010, 12:01 PM
  4. segmentation fault
    By xniinja in forum C Programming
    Replies: 5
    Last Post: 07-09-2010, 01:57 PM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM

Tags for this Thread