0

I have two classes Display and Snake. With the Display class I hols some functionality that involves creating buffer and etc. I'm trying to do something that seem logical to me but apparently not to the compiler

cSnake.h

class Snake 
{
public:
    Snake();
    void printSnake();
    ~Snake();

private:
    Display* display;

};

cSnake.cpp

Snake::Snake()  {}

void Snake::printSnake() {
    display->PrintCharecter(40, 15, L"    Hello World   ");
}

Snake::~Snake() {}

This is the Display class

Class Display{
public:
void CreateScreenBuffer();
void DisplayFrame();
void PrintCharecter(int x, int y LPCWSTR text);
private:
int nScreenWidth;
int nScreenHeight;
wchar_t *screen;
}
// The function that I try to call
void Display::PrintCharecter(int x, int y, LPCWSTR text) {
    wsprintf(&screen[y* nScreenWidth + x], text); // exception is thrown here
}

Calling it in the main

Snake snake
snake.printSnake();

Then it throws unhanded exception that. Being NULL pointer. I bit confused here, which one the NULL pointer is it the function call or the array screen?

Metio_1993
  • 171
  • 10

1 Answers1

0

The error is that the Display pointer points to nothing, which is an uninitialized pointer. A pointer only stores the address of the memory, not the actual memory. Therefore you have only created a pointer, but not the memory it points to on the heap. This means that in your constructor, you should create a new display object on the heap and assign that to your pointer.

Snake::Snake()
{
    display = new Display;
}

This will give you your expected behaviour. It's also important to note that you must delete the memory the pointer points to otherwise it will just float there until the program ends. Therefore your Snake destructor should delete display:

Snake::~Snake()
{
    delete display;
}
Dylan Gentile
  • 146
  • 1
  • 5
  • Better idea: Don't dynamically allocate `display` at all. – user4581301 May 28 '19 at 22:43
  • Also note [The Rule of Three](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). – user4581301 May 28 '19 at 22:44
  • Good point, but if you want the same display object to be pointed to by various other objects, you could instead pass it into the constructor and have many snakes that write to the same the same "display". – Dylan Gentile May 28 '19 at 22:44
  • Truth. [`std::shared_ptr`](https://en.cppreference.com/w/cpp/memory/shared_ptr) can be excellent at solving that problem. – user4581301 May 28 '19 at 22:47
  • Also, I solved the problem with a pointer because the questioner was using a pointer, if I was going to improve the code I'd have a couple other changes(don't create a Display object called display, etc.) and probably wouldn't use a pointer. – Dylan Gentile May 28 '19 at 22:47
  • The `display` pointer is uninitialized. That’s not the same as a null pointer. Still bad, though. – Pete Becker May 28 '19 at 23:03