Why is this causing a segmentation fault?

后端 未结 4 1631
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 21:15

I\'ve been coding this in project in C++, normally I wouldn\'t have too much trouble with a segmentation fault, but I\'m new to C++. Basically I\'m making a pointer to an IntLis

相关标签:
4条回答
  • 2021-01-25 21:41

    Any pointer that has not been initialized has an undefined value, e.g. it probably points to random garbage in the unallocated regions of the heap. Any dereference into an area of the heap which is not allocated is a segmentation fault.

    You need to use the new operator to allocate some heap memory and get the address of that memory. In main:

    IntList *x; // IntList
    x = new IntList();
    

    In prepend:

    IntList *x;
    x = new IntList(); // We now have no need for the local variable y
    x->data = n;
    

    It looks like you wanted to use the address-of operator to point x at y, i.e. x=&y but this will return a pointer to garbage. Any local variable is allocated on the stack and deallocated as soon as the function returns. Never retain a pointer to stack memory after the value pointed to leaves scope, as that memory is likely to be quickly re-allocated to something else, preventing a crash & causing mysterious behavior.

    Look up the delete operator as well.

    0 讨论(0)
  • 2021-01-25 21:47
    IntList *x;
    

    This is uninitialized, and so is the value that it points to.

    0 讨论(0)
  • 2021-01-25 21:48

    Below line just defined a pointer, not malloc memory, so it's pointed to a random address in memory : IntList *x;

    When you try to assign the value "y" to it, program crashes.

    0 讨论(0)
  • 2021-01-25 21:49

    I see two things right off the bat.

    1) In main, you are not allocating an IntList, just an IntList* that points to garbage. When you call x->prepend, you are using uninitialized memory. You need a concrete object before you can call methods on it.

    2) Your prepend method creates a locaion IntList, and returns it, which is a no-no. You're returning an object that had been on the stack and is now no longer valid (though it might work, sometimes. Funny thing, that undefined behavior.)

    0 讨论(0)
提交回复
热议问题