jb167897 jb167897 - 21 days ago 5
C++ Question

C++ Access violation reading location when returning value in an array

I have a member function called

Get
as part of a matrix class structure. This matrix holds the greyscale code for each pixel of an image. The class declares a pointer to private variable

double* matData new double[N*M];


Whenever I call the
Get
function I get the error:

ACCESS VIOLATION READING LOCATION


Here are the two files that I am working with:

Matrix.h



#ifndef MATRIX
#define MATRIX


class Matrix {
public:
Matrix(int sizeR, int sizeC, double* input_data, string n);
double Get(int i, int j) const;
void Set(int i, int j, double val);
~Matrix();
private:
int M; int N;
string name;
double* matData;
};


#endif


Matrix.cpp



#include <iostream>
#include <string>

using namespace std;

#include "matrix.h"

Matrix::Matrix(int sizeR, int sizeC, double* input_data, string n)
{
M = sizeR;
N = sizeC;
name = n;
double* matData = new double[N*M];

cout << "New Matrix '" << name << "' created" << endl;

for (int ii = 0; ii<M*N; ii++)
{
*(matData + ii) = *(input_data + ii);
}
}
Matrix::Get(int i, int j) const
{
return matData[i * N + j];
}
Matrix::Set(int i, int j, double val)
{
matData[i*N + j] = val;
}
Matrix::~Matrix()
{
delete matData;
}


Can someone explain what causes this error and why it's being thrown when I'm returning what is the value at a certain point in an array at the memory location that
matData
is pointing to. Thank you!

Answer

double* matData = new double[N*M]; creates a new pointer inside the constructor. The memory is leaked right away, and the member pointer is still uninitialized.

Remove the double* to refer to the member variable.