Why is this causing a segmentation fault?

后端 未结 4 1652
伪装坚强ぢ
伪装坚强ぢ 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: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.)

提交回复
热议问题