Struct and Pointer Segmentation Error in C

前端 未结 2 542
夕颜
夕颜 2021-01-27 14:32

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 dat         


        
2条回答
  •  执笔经年
    2021-01-27 14:40

    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.

提交回复
热议问题