jb167897 jb167897 - 1 year ago 70
C++ Question

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

I have a member function called

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
function I get the error:


Here are the two files that I am working with:


#ifndef MATRIX
#define MATRIX

class Matrix {
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);
int M; int N;
string name;
double* matData;



#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;
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
is pointing to. Thank you!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download