How to fix 'access violation reading location' in this code in c++

-3

I'm having a problem with this code (c++ in visual studio), the compiler shows this error message: Access violation reading location 0x00000000. The code is for a bank account where you can deposit, withdraw or see your balance and transactions. It seems that the error is in the last line, where it says return 0;.

Note: most of the words are in Spanish.

struct Operaciones {

    int cantidad;
    string fecha;
    string operacion;
    Operaciones(int mCantidad, string mFecha, string mOperacion)
    {
        cantidad = mCantidad;
        fecha = mFecha;
        operacion = mOperacion;
    }
};

class Cuenta {

public:
    Cuenta(); // Constructor por defecto

    float depositar(float r);
    float retirar(float d);
    string consultar();

private:
    float* balance;
    vector<Operaciones> vect;
};

string Cuenta::consultar()
{

    int length = vect.size() - 1;

    cout << "Ultimas 10 operaciones: descendente" << endl;
    cout << "Balance Actual: " << *balance;
    cout << endl;

    int count = 10;
    for (int i = length; i >= 0; --i) {
        cout << endl;
        cout << "Cantidad: " << vect[i].cantidad << endl;
        cout << "Fecha: " << vect[i].fecha << endl;
        cout << "Operacion: " << vect[i].operacion << endl;
        cout << endl;
        --count;

        if (count == 0)
            break;
    }
    return 0;
}
c++
visual-studio
location
access
asked on Stack Overflow Aug 17, 2019 by Biandry Cabrera • edited Aug 17, 2019 by MTMD

1 Answer

0

You have a pointer that points to nothing:

float* balance;

You need to allocate it:

Cuenta::Cuenta() {
    balance = new float;
}

Cuenta::~() {
   delete balance;
}

Or even better, use a std::vector:

class Cuenta {
    //...
private:
    std::vector balance;
    //...
};

string Cuenta::somefunction()
{
    //...
     balance.puch_back(value);
    //...
}

In fact, you have several options that are better than using pointers if you need an array that you don't know the size of ahead of time.


Another problem with your code (as pointed out by @1201ProgramAlarm and @drescherjm) is you are returning 0 as a string. That will throw an error.

Instead, if you want to return an mpty string, you can do this instead:

return "";

Or, you could change your function to return void, if you don't want any return value at all:

void Cuenta::consultar();
answered on Stack Overflow Aug 17, 2019 by Chipster • edited Aug 17, 2019 by Chipster

User contributions licensed under CC BY-SA 3.0