我在C语言中的链表有问题,我只在C++中做过这样的数据结构。
Gdb给了我一个
Program received signal SIGSEGV, Segmentation fault.0x0804a23c in addArg (base=0x1, argument=0x804e410 "is") at myshell.c:4242 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;
  }

最佳答案

似乎currentCmd->args是无效指针可能是指向free()d内存的指针。或者是一个未初始化的指针,或者是一个指向超出范围的局部变量的指针(尽管后面两个似乎不是这样)。
或者您可能意外地重写了程序中其他地方的越界内存。指针问题并不总是出现在失败的地方;有时它们出现在早期的代码中,甚至是不相关的代码中。

10-08 00:49