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't know what is going on Note it crashes when assigning x with y
#include <iostream>
using namespace std;
class a{
private:
int x;
public:
void set_X(int y){
x=y;
}
};
int main()
{
a *Ptr;
Ptr->set_X(5);
}
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 becausethis
pointer isNULL
.You must initialize pointer with some valid memory address of class
a
object.Following can be done,
In this case. It would be better that you should use some smart_ptr like
std::shared_ptr
orstd::unique_ptr
so that you don't need to worry about releasing resources manually.Or
Basic rule: creating a pointer (a variable that contains the address of an object, or otherwise is
NULL
(ornullptr
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.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:
Pointers often point to dynamically allocated objects. If this is what you want, you must use
new
anddelete
accordingly: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: