Moritz Ruge
Moritz Ruge

Reputation: 23

Getopt and Optarg

Hi I am working on a Program in a book. The Program is working almost as it is supposed to, except for one mistake. Every time I try to use the "-l" case I get a Segmentation Fault. Any Ideas?

#include <stdio.h> 
#include <unistd.h>

int main(int argc, char *argv[])
{
    char *lieferung = "";
    int knusprig = 0;
    int zahl = 0;
    char ch;

while ((ch = getopt(argc, argv, "l : k")) != EOF){
    switch (ch) {
        case 'l':
            lieferung = optarg;
            break;
        case 'k':
            knusprig = 1;
            break;
        default:
            fprintf(stderr, "Unbekannte Option: '%s'\n", optarg);
            return 1;
    }
}
argc -= optind;
argv += optind;

if (knusprig)
    puts("Knuspriger Rand.");
if (lieferung[0])
    printf("Zu liefern: %s.\n", lieferung);

puts("Zutaten:");
for (zahl = 0; zahl < argc; zahl++)
    puts(argv[zahl]);
return 0;
}

Thanks in advance.

Upvotes: 0

Views: 308

Answers (2)

dbush
dbush

Reputation: 224127

The third argument get getopt shouldn't contain any spaces. Because there are spaces, it reads this argument as "-l takes no argument, -(space) takes an argument, -(space) takes no argument, and -k takes no argument.

Since getopt doesn't expect -l to pass an argument, optarg is set to NULL, which you then subsequently assign to lieferung. You then dereference that variable, resulting in the segfault.

Git rid of the spaces in the format string:

while ((ch = getopt(argc, argv, "l:k")) != EOF){

Upvotes: 3

Umamahesh P
Umamahesh P

Reputation: 1244

I think the format is incorrect. Replace "l : k" with "l:k".

Upvotes: 1

Related Questions