无法弄清楚seg故障

时间:2016-01-30 02:52:24

标签: c segmentation-fault switch-statement getopt getopt-long

当我尝试在命令行中将-H作为标志传递时,为什么会一直出现设置错误? -h(帮助)工作正常但-H(标题)每次都会混乱。

我有一个main函数,它通过传递argc&来调用parse_command_line。的argc。

bool定义为bool header = false;

文件是char ** file = NULL;

以及我有文件+ = 1的原因;在代码中是这样编译的,因为我使用的是一个将所有警告更改为错误的makefile。

#include "parse.h"              /* prototypes for exported functions */
#include "../main/unused.h"
#include <stdlib.h>
#include <getopt.h>
#include <stdio.h>
#include <stdint.h>

int
parse_command_line (int argc, char **argv, bool *header, char **file)
{
int oc = 0;
file += 1;
bool help = false;
struct option long_options[] = 
{
    {"header", no_argument, NULL, 'H'},
    {"help", no_argument, NULL, 'h'},
    {0, 0, 0, 0}
};

while ((oc = getopt_long(argc, argv, "+Hh", long_options, NULL)) != -1)
{
    printf("The value of oc = %d\n", oc);

    switch(oc)
    {
        case 'h':
            help = true;
            break;
        case 'H':
            printf("inside case H");
            *header = true;
            break;
        case '?':
            fprintf(stderr, "Unknown flag = -%c, type -h or --help for help!\n", optopt);
            exit(EXIT_FAILURE);
            break;
        default:
            break;
    }
}

printf("Out of loop");    if (optind+1 != argc)
{
    fprintf(stderr, "Uh oh, invalid input! Try again with -h or --help for help!\n");
    exit(EXIT_FAILURE);
}

if (help)
{
    printf("\nHaving some trouble? Let me show you the ropes!\n\n");
    printf("Format: ydi <option(s)> mini-elf-file\n\n");
    printf("Here's your options:\n");
    printf("-h --help       Display usage\n");
    printf("-H --header     Show the Mini-Elf header\n");
    exit(1);
}

if (header)
{
    printf("Inside HEader");
    FILE *file;
    uint16_t nums[6];
    file = fopen(argv[optind], "r");

    #define STRUCT_ITEMS 7
    fread(nums, 16, 6, file);
    int cur_print;
    for (cur_print = 0; cur_print < STRUCT_ITEMS; cur_print++)
    {
        printf("%d ", nums[cur_print]);
    }
}
return 0;
} 

我的parse.h文件如下:

#ifndef __PARSE_COMMAND_LINE__
#define __PARSE_COMMAND_LINE__
#include <stdbool.h>

int parse_command_line (int argc, char **argv, bool *header, char **file);

#endif

还有其他文件,例如elf.h和elf.c,我没有实现,此时根本没有调用,这让我相信它们不会成为问题而且不会需要发布小2行文件。我的主要功能如下:

#include <stdio.h>              /* standard I/O */
#include <stdlib.h>
#include "unused.h"             /* UNUSED macro */
#include "../cmdline/parse.h"   /* command line parser */
#include "../y86/elf.h"         /* Mini-ELF format */

int
main (int argc UNUSED, char **argv UNUSED)
{
  printf ("Congratulations, you have compiled your source code!\n");
  bool header = false;
  char **file = NULL;
  parse_command_line (argc, argv, &header, file);
  return 0;
}

文件unused.h(因为编译器会使未使用的变量成为错误而不是警告)如下:

#ifndef __UNUSED__
#define __UNUSED__
#define UNUSED __attribute__ ((unused))
#endif

1 个答案:

答案 0 :(得分:0)

代码不检查fopen的返回值,如果出错,它将为NULL。在fread调用中取消引用NULL会导致段错误。

相关问题