C中链表示例的奇怪核心转储错误

时间:2016-12-10 06:28:57

标签: c pointers linked-list coredump

我有以下程序。我想练习链接列表,并尝试构建一个应用程序,可以将输入程序的标志保存到链接列表中我的所有控件都正常工作,但是当我输入所有内容而不是列出标志时,我得到一个核心转储错误

- UPDATE -

该程序应该检查提供给程序的标志是否有效或需要任何值,如果一切正常,它应该打印到控制台的键值对,它们存储在链表中 我通过调用gcc test.c init.c编译程序并运行为./a.out -test someParam

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "init.h"
//f for false t for true
const char *flgs[3][2] = {{"-test", "t"}, {"-hey", "f"}, {"-heydehey", "f"}};
int forEach(FLAGS *flags, void (*cb)(char *flag, char *vl)) {
  FLAGS *current = flags;
  if (current == NULL) {
    return -1;
  }
  while (current != NULL) {
    cb(current->flag, current->value);
    current = current->next;
  }
  return 0;
}
FLAGS *initArgs(int argc, char **argv) {
  if (argc < 2) {
    return NULL;
  }
  int flagsNum = 3;
  FLAGS *rtr = malloc(sizeof(FLAGS));
  if (rtr == NULL) {
    fprintf(stderr, "unable to allocate memory\n");
    exit(-1);
  }
  FLAGS *current = NULL;
  rtr->next = current;
  bool invalidFlag = true;
  bool skipNext = false;
  for (int i = 1; i < argc; i++) {
    if (skipNext) {
      skipNext = false;
      continue;
    }
    invalidFlag = true;
    if (argv[i][0] == '-') {
      // if flag
      current = malloc(sizeof(FLAGS));
      for (int f = 0; f < 3; f++) {
        if (!strcmp(argv[i], flgs[f][0])) {
          invalidFlag = false;
          if (flgs[f][1] == "t") {
            if (i + 1 == argc || argv[i + 1][0] == '-') {
              fprintf(stderr, "flag %s requires a value ,none given\n", argv[i]);
              exit(-1);
            }
            current->value = argv[i + 1];
            current->next = NULL;
            current = current->next;
            skipNext = true;
          }
          current->flag = argv[i];
        }
      }
      if (invalidFlag) {
        fprintf(stderr, "\x1B[31minvalid flag %s\n", argv[i]);
        exit(-1);
      }
    }
  }
  return rtr;
}

这是我的init.h和test.c文件

test.c的

#include <stdio.h>
#include <stdlib.h>
#include "init.h"
void cb(char *, char *);
int main(int argc, char **argv) {
  FLAGS *entered = initArgs(argc, argv);
  if (entered == NULL) {
    fprintf(stderr, "an error occured\n");
    return -1;
  }
  forEach(entered, &cb);
  return 0;
}
void cb(char *fl, char *val) { printf("flag=%s; value=%s;\name", fl, val);
 }

init.h里

#define true 1
#define false 0
typedef int bool;
typedef struct values {
  char *flag;
  char *value;
  struct values *next;
} FLAGS;
extern const char *flgs[3][2];
int forEach(FLAGS *, void (*cb)(char *, char *));
FLAGS *initArgs(int argc, char **argv);

1 个答案:

答案 0 :(得分:2)

看看这些行和我的评论:

        current->next = NULL;      // Here current->next becomes NULL
        current = current->next;   // so here current becomes NULL
        skipNext = true;
      }
      current->flag = argv[i];     // So here you dereference NULL

因此你得到一个核心转储。