Hi,
I'm doing a project in my text book about Link-List called "Pile of Books". I am trying to create a remove method that removes the first node in the list. However the code I cam up with gives me a "read access violation. _Right_data was nullptr." exception when i try to compile and run the program.
I narrowed the problem down to the line in "headPtr = headPtr->getNext();" in the remove() method, but I am not sure why this is, as I've basically used the same code in a previous assignment and it worked. Here is all my code:
//PileOfBooksInterface.h
#pragma once
#include <string>
#include <vector>
class PileOfBooksInterface
{
public:
/** Adds a book to the top of the pile
@param addBook is a string of the title of the book the client wants to add to the top of the pile
@returns true is book is succesfuly added, and false otherwise*/
virtualbool add(std::string addBook) = 0;
/** Removes the top book from the pile if the pile is not empty
@returns true is book is successfuly removed and false otherwise*/
virtualbool remove() = 0;
/** Removes all books from the pile */
virtualvoid emptyOut() = 0;
/** Puts all books in the pile to a vector
@return a Vector of the pile of books */
virtual std::vector<std::string> toVector() = 0;
};
//PileofBooks.h
#pragma once
#include "PileofBooksInterface.h"
#include <string>
#include <vector>
//#include "Node.h"
#include "Node.cpp"
class PileOfBooks : public PileOfBooksInterface
{
private:
Node<std::string>* headPtr; // Pointer to first node
int itemCount; // Current count of bag items
// Returns either a pointer to the node containing a given entry
// or the null pointer if the entry is not in the bag.
//Node<std::string>* getPointerTo(const std::string& target) const;
public:
/** Construct an empty pile of books */
PileOfBooks();
/** Destructure */
~PileOfBooks();
/** Adds a book to the top of the pile
@param addBook is a string of the title of the book the client wants to add to the top of the pile, title must not be an empty string
@returns true is book is succesfuly added, and false otherwise*/
bool add(std::string addBook);
/** Removes the top book from the pile if the pile is not empty
@returns true is book is successfuly removed and false otherwise*/
bool remove();
/** Removes all books from the pile */
void emptyOut();
/** Puts all books in the pile to a vector
@return a Vector of the pile of books */
std::vector<std::string> toVector();
};
The crash occurs in toVector(). The problem is that you use (unnecessarily) itemCount. PileOfBooks::remove() does not decrease itemCount. Therefore you get a nullptr.
I would suggest to eliminate itemCount entirely.
To solve your current problem you can add --itemCount; somewhere between line 39 and 45 in PileOfBooks::remove().