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

前端 未结 3 787
名媛妹妹
名媛妹妹 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);
    
    0 讨论(0)
  • 2021-01-29 06:05
    a *Ptr;
    Ptr->set_X(5);
    

    Your Ptr does not point to anything. Trying to invoke a member function on an uninitialised pointer results in undefined behaviour. Crashing is just one of the many more or less random things that can happen.

    Luckily, in your example, you do not need a pointer anyway. You can simply write:

    a my_a;
    my_a.set_X(5);
    

    Pointers often point to dynamically allocated objects. If this is what you want, you must use new and delete accordingly:

    a *Ptr = new a;
    Ptr->set_X(5);
    delete Ptr;
    

    In modern C++, std::unique_ptr is typically a superior alternative because you don't have to manually release the allocated memory, which removes a lot of potential programming errors:

    auto Ptr = std::make_unique<a>();
    Ptr->set_X(5);
    // no delete necessary
    
    0 讨论(0)
  • 2021-01-29 06:06

    Basic rule: creating a pointer (a variable that contains the address of an object, or otherwise is NULL (or nullptr since 2011)) as pointed out by Christian Hackl in comments) does not create a corresponding pointee (an object who's address can be stored in the pointer).

    More formally, Ptr is an uninitialised pointer. Even accessing its value gives undefined behaviour (e.g. some_other_pointer = Ptr). For operator -> to work correctly, the pointer must first be initialised so it points at a valid object.

     a aobj;
     a *Ptr = &aobj;
     Ptr->set_X(42);   // OK
    
     a *Ptr2 = new a;
     Ptr2->set_X(42);    // OK
     delete Ptr2;
    
    0 讨论(0)
提交回复
热议问题