Metio_1993
Metio_1993

Reputation: 171

Exception Unhandled while trying to initialize dynamic array

I'm allocating dynamic memory in my class as a private: variable

Then in the constructor I'm trying to initialize the array.

public
Display(int Width, int Height) {
    nScreenHeight = Height;
    nScreenWidth = Width;
    DWORD dwBytesWritten = 0;
    for (int i = 0; i < (nScreenWidth*nScreenHeight); i++) screen[i] = L'';
    SetConsoleActiveScreenBuffer(hConsole);
}

private:
    int nScreenWidth;
    int nScreenHeight;
    wchar_t *screen = new wchar_t[nScreenWidth*nScreenHeight];

If I try run the program an Exception Unhanded in thrown.

Unhandled exception thrown: write access violation. this->screen was 0x2096112.

While trying to initialize the buffer screen with L' '

Upvotes: 0

Views: 154

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122486

Memebers are initialized in the order they appear in the class declaration before the body of the constructor is executed. So what happens is:

  • nScreenWidth is default initialized (see here)
  • nScreenHeight is default initialized
  • screen is initialized with new wchar_t[nScreenWidth*nScreenHeight]
  • only now the constructor runs and you assign values to nScreenWidth and nScreenHeight

Use the initializer list for all members to avoid confusion:

Display(int Width, int Height) : 
   nScreenWidth(Width), nScreenHeight(Height), screen(new wchar_t[nScreenWidth*nScreenHeight])
{
    DWORD dwBytesWritten = 0;
    for (int i = 0; i < (nScreenWidth*nScreenHeight); i++) screen[i] = L'';
    SetConsoleActiveScreenBuffer(hConsole);
}

Even better would be to use a std::vector<wchar_t>, the constructor would be

Display(int Width, int Height) : 
       nScreenWidth(Width), nScreenHeight(Height), screen(Width*Height)
{
    ...

and instead of bothering about the rule of three/five you can rely on the rule of zero.

Upvotes: 3

Related Questions