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

查看:91
本文介绍了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\n");

  if(l.key > temp->key) {
    printf(" 1\n");
    temp->next = &l;
    l.previous = temp;
  }
  else {
    printf(" 2\n");
    l.previous = temp->previous;
    l.next = temp;
    printf( "2.2\n");
    if(temp->previous) {
      //printf("%i\n",temp->previous->key);
      temp->previous->next = &l;
    }
    printf(" 2.3\n");
    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天全站免登陆