gpt4 book ai didi

c - C 中链接列表示例中奇怪的核心转储错误

转载 作者:行者123 更新时间:2023-11-30 18:50:02 26 4
gpt4 key购买 nike

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

--更新--

程序应该检查提供给程序的标志是否有效或需要任何值,如果一切正常,它应该将存储在链接列表中的键值对打印到控制台我通过调用 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 文件

测试.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);

最佳答案

看看这些行和我的评论:

        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

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

关于c - C 中链接列表示例中奇怪的核心转储错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41072852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com