C中的结构和指针分段错误 [英] Struct and Pointer Segmentation Error in C

查看:31
本文介绍了C中的结构和指针分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以帮助我解决这个分段错误.这段代码很简单,但错误很难弄清楚.

can anyone help with this segmentation error i keep getting. this code is simple but the error is so hard to figure out.

struct Link {
  int key;
  unsigned data: 2;
  struct Link *next;
  struct Link *previous;
};

struct Link* addInOrder(struct Link *, struct Link);

int main() {
  struct Link *head;
  struct Link data1;
  struct Link data2;
  struct Link data3;
  data1.key = 25;
  data1.data = 1;
  data1.next = NULL;
  data2.key = 50;
  data2.data = 0;
  data2.next = NULL;
  data3.key = 100;  
  data3.data = 2; 
  data3.next = NULL;
  head = NULL;
  head = addInOrder(head, data2);
}

struct Link* addInOrder(struct Link *srt, struct Link l) {
  if(!srt) {
    return &l;
  }

  struct Link *temp = srt;
  while(temp->next && l.key > temp->key)
    temp = temp->next;

  printf("here
");

  if(l.key > temp->key) {
    printf(" 1
");
    temp->next = &l;
    l.previous = temp;
  }
  else {
    printf(" 2
");
    l.previous = temp->previous;
    l.next = temp;
    printf( "2.2
");
    if(temp->previous) {
      //printf("%i
",temp->previous->key);
      temp->previous->next = &l;
    }
    printf(" 2.3
");
    temp->previous = &l;
  }
  return srt;
}

我在 addInOrder() 的第一行不断收到错误消息.编译器所说的都是分段错误.

i keep getting an error at the first line in addInOrder(). all the compiler says is Segmentation Error.

另外,如果我在 if 语句之后添加 printf("..."); 并运行它...不会打印

also, if i add printf("..."); right after the if statement and run it ... does not print

推荐答案

您正在通过值(struct Link l)传递 addInOrder() 的第二个参数.这会在您调用函数时创建参数的副本,并且在 addInOrder() 中,l 存在于堆栈中.然后,您将返回局部变量的地址并将其分配给 head,但是当函数退出时,该变量超出范围并被释放.所以你给 head 分配了一个无效的地址,这会导致一个段错误.

You're passing the second argument of addInOrder() by value (struct Link l). This creates a copy of the argument when you call the function, and in addInOrder(), l exists on the stack. You're then returning the address of the local variable and assigning it to head, but when the function exits, that variable is out of scope and is deallocated. So you're assigning an invalid address to head, and that results in a segfault.

这篇关于C中的结构和指针分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆