Jean Finley
Jean Finley

Reputation: 517

Access violation when using std::vector

I'm getting the following error:

Pointing to the size() method of vector.h. It seems to happen when this method is used:

void Player::printInventory(){
    if(inventory.size() != 0){
        for(unsigned int i=0; i<inventory.size(); i++){
            cout<<inventory[i] << endl;
        }
    }
}

Full code:

Player.h:

#pragma once
#include <vector>
#include <memory>

using namespace std;

class Player
{
private:
    int health;
    string name;
    vector<int> inventory;

public:
    Player(void);
    Player(string);
    ~Player(void);
    void changeHealth(int);
    void addToInventory(int);
    void removeFromInventory(int);
    void printInventory();
};

Player.cpp:

#include "Player.h"
#include <iostream>
#include <string.h>

Player::Player(void)
{
    health = 20;
}

Player::Player(string newName)
{
    name = newName;
    health = 20;
}

Player::~Player(void)
{
}

void Player::changeHealth(int amount){
    health += amount;
}

/*void Player::addToInventory(int item){
    inventory.push_back(item);
}

void Player::removeFromInventory(int itemID){

    for(unsigned int i=0; i<inventory.size(); i++){
        if(inventory[i] == itemID)
            inventory.erase(inventory.begin()+i);
    }

}*/

void Player::printInventory(){
    if(!inventory.empty()){
        for(unsigned int i=0; i<inventory.size(); i++){
            cout<<inventory[i] << endl;
        }
    }
}

main:

#include "World.h"
#include "Player.h"
#include <iostream>
#include <memory>

World world;

void main(){

    unique_ptr<Player> player(new Player("Ted"));
    world.setPlayer(move(player));
    int selection = 0, inventoryOption = 0, exitOption = 0;

    do{
        inventoryOption = 0;
        exitOption = inventoryOption + 1;

        cout<< inventoryOption <<". View Inventory"<<endl;
        cout<< exitOption <<". Quit game";

        cin>>selection;

        if(selection == inventoryOption){
            player->printInventory();
        }
        else{
        }


    }while(selection != exitOption);

}

Please excuse the messiness, this code is butchered from previous code which has the same errors.

Upvotes: 0

Views: 4553

Answers (3)

ForEveR
ForEveR

Reputation: 55887

Use !inventory.empty() instead inventory.size() != 0. So, for code, when you move unique_ptr, unique_ptr will be release, so it`ll point to zero.

Upvotes: 1

Daniel
Daniel

Reputation: 31579

Looks like you are using some null object. Print the value of this(Player) in the function just before the crash.

Upvotes: 0

Seth Carnegie
Seth Carnegie

Reputation: 75130

You're moveing the unique_ptr so that it no longer points to the new Player, then you're using it:

world.setPlayer(move(player));

...

player->printInventory();

Don't use move just to make the code compile; use shared_ptr so you can have multiple pointers to the object.

Upvotes: 5

Related Questions