Struct and Pointer Segmentation Error in C

前端 未结 2 541
夕颜
夕颜 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.

    0 讨论(0)
  • 2021-01-27 14:43

    The part (and everywhere &l is used)

    if (!srt)
        return &l;
    

    is returning the address of a stack variable. Your addInOrder function should probably have the signature

    struct Link* addInOrder(struct Link* srt, struct Link* l);
    
    0 讨论(0)
提交回复
热议问题