我在 C 中使用链表时遇到问题,我只在 C++ 中完成了诸如此类的数据结构。
Gdb 给了我一个
Program received signal SIGSEGV, Segmentation fault.
0x0804a23c in addArg (base=0x1, argument=0x804e410 "is") at myshell.c:42
42 while ( (curr != NULL) && (curr->n != NULL) )
我熟悉与内存有关的分段错误,但是我认为我已经正确分配了内存。我究竟做错了什么?
addArg 被称为addArg(currentCmd->args, lexeme);
并且 currentCmd 是指向节点结构的指针
struct lnode {
char *x;
struct lnode *n;
};
struct node
{
char *command;
struct lnode *args;
int input;
int output;
int error;
char *in;
char *out;
char *err;
struct node *next;
struct node *prev;
};
void addArg(struct lnode *base, char *argument)
{
struct lnode *curr = base;
//this is line 42
while ( (curr != NULL) && (curr->n != NULL) )
curr = curr->n;
curr -> n = malloc(sizeof(struct lnode));
curr = curr->n;
curr->x = strdup(argument);
curr->n = NULL;
}
struct node* createNode(char *command_, int input_, int output_, int error_, char *in_, char *out_, char *err_, struct node *prev_)
{
struct node *n;
n = malloc(sizeof (struct node));
n->command = strdup(command_);
n->prev = prev_;
n->next = NULL;
n->input = input_;
n->output = output_;
n->error = error_;
n->in = in_;
n->out = out_;
n->err = err_;
n->args=malloc(sizeof(struct lnode));
return n;
}