c - 带链表的段错误

标签 c linked-list segmentation-fault

我在 C 中使用链表时遇到问题,我只在 C++ 中完成过这样的数据结构。

Gdb 正在给我一个

程序收到信号 SIGSEGV,段错误。 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;
  }

最佳答案

看起来 currentCmd->args 是一个无效指针。可能是指向 free() 内存的指针。或未初始化的指针,或指向超出范围的局部变量的指针(尽管后两者在这里似乎不是这种情况)。

或者您可能不小心覆盖了程序中其他地方的越界内存。指针问题并不总是在失败点;有时它们在较早的代码中,甚至是不相关的代码中。

关于c - 带链表的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13434874/

相关文章:

c - 正确使用 fgets()

c - C 的内存库?

optimization - 找到两个链表与重复项的交集

c - 链表打印段错误

c++ - 在cpp LinkedList程序中将两个多项式相乘

c - fputs 中的 fgets 给出段错误

c - 段错误何时发生?

将 char 转换为 unsigned int - C

c# - 错误 : SIGSEGV when running application on Mono

c - 如何从静态库创建共享对象文件