vc++ Access violation reading location

-1

I'm getting a error:

First-chance exception at 0x0021F4F2 in Tetris.exe: 0xC0000005: Access violation reading location 0x000000D8.
Unhandled exception at 0x0021F4F2 in Tetris.exe: 0xC000041D: An unhandled exception was encountered during a user callback.

Here is my ColorGrid.cpp file, error happens when I run the application at function name const COLORREF ColorGrid::Index(int iRow, int iCol) & line return m_buffer[iRow * COLS + iCol];

#include "StdAfx.h"
#include "ColorGrid.h"
#include <exception> 


ColorGrid::ColorGrid()
{

}
COLORREF& ColorGrid::Index(int iRow, int iCol)
{
    bool flag = false; 
    if ((iRow >= 0) && (iRow < ROWS) && (iCol >= 0) && (iCol < COLS))
    {
        flag = true; 
    }
    if (!flag)
    {
        TRACE("iRow:", iRow, " iCol:", iCol);
    }
    return m_buffer[iRow + COLS + iCol];
}

const COLORREF ColorGrid::Index(int iRow, int iCol) const
{
    try
    {

        bool flag = false;
        if ((iRow >= 0) && (iRow < ROWS) && (iCol >= 0) && (iCol < COLS))
        {
            flag = true;

        }
        if (!flag)
        {
            TRACE("iRow:", iRow, " iCol:", iCol);

        }

        return m_buffer[iRow * COLS + iCol];

    }
    catch (CException* e)
    {
        TCHAR   szCause[255];
        CString strFormatted;
        e->GetErrorMessage(szCause, 255);
        TRACE("exception GetErrorMessage:", szCause);
        TRACE("iRow:", iRow, " iCol:", iCol, "COLS:", COLS);
        e->Delete(); 
    }

}

Related header file ColorGrid.h:

#ifndef COLOR_GRID_H
#define COLOR_GRID_H
const int ROWS = 20; 
const int COLS = 10; 
class ColorGrid
{
public:
    ColorGrid(); 
    void Clear(); 
    COLORREF& Index(int iRow, int iCol);
    const COLORREF Index(int iRow, int iCol) const; 

    void Serialize(CArchive& archive);

private:
    COLORREF m_buffer[ROWS * COLS];
};
#endif

Is this because I pre-allocated/initialized m_buffer[ROWS * COLS] in header & later I want to return m_buffer[iRow * COLS + iCol];return a different size?

Thanks

c++
visual-c++
asked on Stack Overflow Mar 7, 2018 by cyber101 • edited Mar 7, 2018 by PravinS

2 Answers

1

The clue is in the error message Access violation reading location 0x000000D8 your code is trying to access a very low address, this address is not available to normal programs. This will be caused by trying to use a null pointer. Given the offset from null is quite large I assume m_buffer is null.

answered on Stack Overflow Mar 7, 2018 by Alan Birtles
1

What is the value of 'iRow' and 'iCol' when exception of access violation.

if the sum of 'iRow * COLS + iCol' is greater than 199 then it should throw the access violation.

One think I don't understand why are you returning " return m_buffer[iRow * COLS + iCol]" always in that function. It is better to return when the flag is true.

Thanks.

answered on Stack Overflow Mar 7, 2018 by Manivasakan

User contributions licensed under CC BY-SA 3.0