the arrow '->' separator is crashing when calling function from class

前端 未结 3 786
名媛妹妹
名媛妹妹 2021-01-29 05:46

I\'m working on a project for class and I\'m using classes and pointers of type class to call some functions in the class but it\'s crashing on Code Blocks and Eclipse and I don

3条回答
  •  清酒与你
    2021-01-29 06:03

    You have just declared a pointer variable of type a* but it doesn't point to a valid memory address. And since you are calling a member function via that pointer which updates a data-member hence you have segfault because this pointer is NULL.

    You must initialize pointer with some valid memory address of class a object.

    Following can be done,

    a* ptr = new a;
    ptr->set_X(5);
    // ...
    delete ptr;
    

    In this case. It would be better that you should use some smart_ptr like std::shared_ptr or std::unique_ptr so that you don't need to worry about releasing resources manually.

    Or

       a* ptr;
       a aobj_;
       ptr = &aobj_;
       ptr->set_X(5);
    

提交回复
热议问题