You have not assigned anything to the pointers to the Paddle
, Ball
or Manager
variables in your main method.
By default the won’t be initialised and will point somewhere in memory, which may or may not be accessible to your application. When you access them and the memory is inaccessible you get the access violation or segfault you’re observing.
There are two approaches you could take. If you change your main as follows:
int main()
{
Paddle p1;
Paddle p2;
Ball b;
Manager m;
m.Run(&p1,&p2,&b);
return 0;
}
Then an instance of each of the classes will exist on the stack. Since the application exits once m.Run
returns it’s safe to use this approach as the lifetime of the objects is longer than the code called by Run
.
Alternatively you can allocate them on the heap. In this case you can use:
int main()
{
std::unique_ptr<Paddle>( new Paddle );
std::unique_ptr<Paddle>( new Paddle );
std::unique_ptr<Ball>( new Ball );
std::unique_ptr<Manager>( new Manager );
m->Run(p1.get(),p2.get(),b.get());
return 0;
}
The unique_ptr
will hold a pointer to a Paddle
etc allocated on the heap and will automatically clean it up for you once the main
method returns.
2
solved Pointers give seg fault [closed]