C++ Exception thrown: read access violation. this was nullptr - c++

For one of my programming classes, we are required to design a program that can be ran through the provided "stress tests" that our instructor wrote himself.
We are working with nodes and linked lists but in a way that is different than any of the YouTube videos I have looked at on the subject.
I've been tearing my hair out for the past couple of days trying to figure out what is wrong with my program but I'm having no luck.
Here is the code for my Node.cpp file (didn't include Node.h)
#include "Node.h"
Node::Node() {
m_value = 0;
m_next = nullptr;
}
void Node::setValue(int val) {
m_value = val;
}
int Node::getValue() const {
return m_value;
}
void Node::setNext(Node* prev) {
m_next = prev;
}
Node* Node::getNext() const {
return m_next;
}
Here is my LinkedList.cpp
#include <iostream>
#include <vector>
#include "LinkedList.h"
LinkedList::LinkedList() {
m_front = nullptr;
m_size = 0;
}
LinkedList::~LinkedList() {
// Deconstructor
m_size = 0;
Node* a = m_front;
Node* b = a->getNext();
while (a->getNext() != NULL) {
delete a;
a = b;
b = b->getNext();
}
delete a;
a = NULL;
}
bool LinkedList::isEmpty() const{
if (m_size == 0) {
return true;
}
else {
return false;
}
}
int LinkedList::size() const {
return m_size;
}
bool LinkedList::search(int value) const {
if (m_size == 0) {
return false;
}
else if (m_size == 1) {
if (m_front->getValue() == value) {
return true;
}
else {
return false;
}
}
else {
Node* a = m_front;
for (int i = 0; i < m_size; i++) {
if (a->getValue() == value) {
return true;
}
else {
a = a->getNext();
}
}
return false;
}
}
void LinkedList::printList() const {
std::cout << "List: ";
if (m_size == 0) {
// Print Nothing
}
else if (m_size == 1) {
std::cout << m_front->getValue();
}
else {
Node* a = new Node();
a = m_front;
int b = m_front->getValue();
std::cout << b << ", ";
while (a->getNext() != NULL) {
a = a->getNext();
if (a->getNext() == NULL) {
std::cout << a->getValue();
}
else {
std::cout << a->getValue() << ", ";
}
}
}
std::cout << std::endl;
}
void LinkedList::addBack(int value) {
Node* a = new Node();
a->setValue(value);
if (m_size == 0) {
m_front = a;
}
else {
Node* b = new Node();
b = m_front;
while (b->getNext() != NULL) {
b = b->getNext();
}
b->setNext(a);
}
m_size++;
}
void LinkedList::addFront(int value) {
Node* a = new Node(); // Check later
a->setNext(m_front);
a->setValue(value);
m_front = a;
m_size++;
}
bool LinkedList::removeBack() {
if (m_size == 0) {
return false;
}
else {
Node* a = new Node();
Node* b = new Node();
a = m_front;
while (a->getNext() != NULL) {
b = a;
a = a->getNext();
}
b->setNext(nullptr);
delete a;
a = NULL;
m_size--;
return true;
}
}
bool LinkedList::removeFront() {
if (m_size == 0) {
return false;
}
else {
Node* a = new Node();
a = m_front;
m_front = m_front->getNext();
delete a;
a = NULL;
m_size--;
return true;
}
}
std::vector<int> LinkedList::toVector() const {
if (m_size == 0) {
std::vector<int> b;
return b;
}
else {
std::vector<int> a(m_size);
Node* b = new Node();
b = m_front;
for (int i = 0; i < m_size; i++) {
a[i] = b->getValue();
b = b->getNext();
}
return a;
}
}
Basically, I've tested my program on my own and I've been able to make a linked list and run all my add and remove functions and print out the lists just fine. My problem is I run the test that our instructor gave us and it looks like this at the point where I'm having problems (Those print messages are in another file but all they seem to do is print the string arguments that are passed)
int score = 0;
const int MAX_SCORE = 90;
std::cerr << "\n\n=========================\n";
std::cerr << " RUNNING TEST SUITE \n";
std::cerr << "=========================\n\n";
//Run test and award points where appropriate
score += test1() ? 2 : 0;
score += test2() ? 2 : 0;
score += test3() ? 3 : 0;
This goes on for 18 tests, but my program never "makes" it past the first one. It passes the first test then all of a sudden throws an error.
bool Test_LinkedList::test1()
{
LinkedList list;
bool isPassed = false;
printTestMessage("size of empty list is zero");
isPassed = list.size() == 0;
printPassFail(isPassed);
return (isPassed);
}
I actually get this output before it crashes
=========================
RUNNING TEST SUITE
=========================
Test 1: size of empty list is zero: PASSED
So it passes the first test but never makes it out of there. What I mean is that I have tried throwing in a cout message around
score += test1() ? 2 : 0;
std::cout << "Done with test 1"
score += test2() ? 2 : 0;
score += test3() ? 3 : 0;
But that is never outputted. Instead my program breaks and Visual Studio pops up with a message saying
Exception thrown: read access violation.
this was nullptr.
If there is a handler for this exception, the program may be safely continued.
Then it points me to my method in Node.cpp that is
Node* Node::getNext() const {
return m_next;
}
Sorry, I know this is a lot of text to read through but right now I'm beyond stumped and there is no time for me to go into office hours as it is due early tomorrow morning.
edit: i tried omitting the first test and running it. It gets through the next 6 tests but then fails on the 7th (8th) with the same exact error.
bool Test_LinkedList::test8()
{
LinkedList list;
bool isPassed = false;
printTestMessage("search returns false on empty list");
isPassed = !list.search(42);
printPassFail(isPassed);
return (isPassed);
}

The LinkedList destructor has a couple of problems. First, it's pointless to set m_size to 0 and a to NULL since they will both go away at the end of the destructor. More important, the code will attempt to dereference a null pointer when the list is empty:
Node* a = m_front; // okay, gets that head pointer
Node* b = a->getNext(); // bang!!
Here's a cleaner way to write it:
Node* a = m_front;
while (a != NULL) {
Node *temp = a->getNext();
delete a;
a = temp;
}

Related

Implementation of Queue in C++

When I study the DataStructrue in my school, I implemented the Queue.
School's DataStructure class process is below.
student implemnted the DS
student submit in Domjudge
Domjudge score the code based by test cases.
My freind implemented the Queue like below.
#include <iostream>
#include <string>
using namespace std;
class Node {
public:
int data;
Node* next;
Node() {}
Node(int e) {
this->data = e;
this->next = NULL;
}
~Node(){}
};
class SLinkedList {
public:
Node* head;
Node* tail;
SLinkedList() {
head = NULL;
tail = NULL;
}
void addFront(int X) {
Node* v = new Node(X); // new Node
if (head == NULL) {
// list is empty
head = tail = v;
}else {
v->next = head;
head = v;
}
}
int removeFront() {
if (head == NULL) {
return -1;
}else{
Node* tmp = head;
int result = head->data;
head = head->next;
delete tmp;
return result;
}
}
int front() {
if (head == NULL) {
return -1;
}else {
return head->data;
}
}
int rear() {
if (head == NULL) {
return -1;
}else {
return tail->data;
}
}
int empty() {
if (head == NULL) {
return 1;
}else {
return 0;
}
}
void addBack(int X) {
Node* v = new Node(X);
if (head == NULL) {
head = tail = v;
}else {
tail->next = v;
tail = v;
}
}
~SLinkedList() {}
};
class LinkedQ {
public:
int n = 0;
int capacity;
Node* f;
Node* r;
SLinkedList Q;
LinkedQ(int size) {
capacity = size;
f = NULL;
r = NULL;
}
bool isEmpty() {
return n == 0;
}
int size() {
return n;
}
int front() {
return Q.front();
}
int rear() {
return Q.rear();
}
void enqueue(int data) {
if (n == capacity) {
cout << "Full\n";
}else {
Q.addBack(data);
n++;
}
}
};
int main() {
int s, n;
string cmd;
cin >> s >> n;
listQueue q(s);
for (int i = 0; i < n; i++) {
cin >> cmd;
if (cmd == "enqueue") {
int x;
cin >> x;
q.enqueue(x);
}else if (cmd == "size") {
cout << q.size() << "\n";
}else if (cmd == "isEmpty") {
cout << q.isEmpty() << "\n";
}else if (cmd == "front") {
q.front();
}else if (cmd == "rear") {
q.rear();
}
}
}
And I implmented like this (Node class and main are same, So I pass the code)
#include <iostream>
#include <string>
using namespace std;
class Node{...};
class listQueue {
public:
Node* head;
Node* tail;
int capacity;
int n = 0;
listQueue() {
head = NULL;
tail = NULL;
}
void enqueue(int X) {
Node* v = new Node(X); // new Node
if (n==capacity) {
cout << "Full\n";
return;
}
if (head == NULL) {
// Queue is empty
head = tail = v;
}else {
v->next = head;
head = v;
}
}
int front() {
if (head == NULL) {
return -1;
}else {
return head->data;
}
}
int rear() {
if (head == NULL) {
return -1;
}else {
return tail->data;
}
}
int empty() {
if (head == NULL) {
return 1;
}else {
return 0;
}
}
~listQueue() {}
};
test cases are just enqueue
but my friend is correct, and my code has occured memory over error.
So I check the usage of memory in Domjudge, My friend code and My code has very big gap in memory usage.
Why these two codes have memory usage gap big?
P.S I can't speak English well. If there is something you don't understand, please tell me.
First, rear is incorrect. It checks head and return tail. It happens to correct when you first set head=tail=v but it might get wrong later.
int rear() {
if (head == NULL) {
return -1;
}else {
return tail->data;
}
}
Check the if statement below:
v is leaked if queue is full in enqueue in your implementation.
Don't use NULL in C++. You may refer to NULL vs nullptr (Why was it replaced?).
void enqueue(int X) {
Node* v = new Node(X); // new Node
if (n==capacity) { // You're leaking v;
cout << "Full\n";
return;
}
if (head == NULL) {
// Queue is empty
head = tail = v;
}else {
v->next = head;
head = v;
}
}

Copy constructor and assignemnt operator overload not working in C++

I am implementing a HashMap class with a destructor, copy constructor and assignment operator. When the I create a HashMap object and add a key and value to it and try assigning it to a new empty object I get a "double free or corruption" error. However if I do the same without adding any keys to the HashMap the code runs fine. I also noticed that if I comment out the arrayCopy function from the assignment operator overload implementation the code also runs fine but off course the object that I am assigning into wont have a copy of the array. The BackTrace also says that the error is on this line:
else if (node->next == nullptr)
Any help is appreciated, Thanks!
HashMap::HashMap()
:hasher{hash}, Buckets_Array{new Node* [initialBucketCount]}, currentBucketCount{initialBucketCount}, sz{0}
{
fillArray(Buckets_Array, currentBucketCount);
}
HashMap::HashMap(const HashMap& hm)
:hasher{hm.hasher}, Buckets_Array{new Node*[hm.currentBucketCount]},currentBucketCount{hm.currentBucketCount}, sz{hm.sz}
{
arrayCopy(hm.Buckets_Array, Buckets_Array, currentBucketCount);
}
HashMap::~HashMap()
{
for(int i = 0; i < currentBucketCount; i++)
{
deleteLinkedList(Buckets_Array[i]);
}
delete[] Buckets_Array;
}
HashMap& HashMap::operator=(const HashMap& hm)
{
if (this != &hm)
{
Node** newNodeArray = new Node*[currentBucketCount];
fillArray(newNodeArray, currentBucketCount);
arrayCopy(hm.Buckets_Array, newNodeArray, currentBucketCount);
currentBucketCount = hm.currentBucketCount;
sz = hm.sz;
for (int i = 0; i < currentBucketCount; i++)
{
deleteLinkedList(Buckets_Array[i]);
}
delete[] Buckets_Array;
Buckets_Array = newNodeArray;
}
return *this;
}
void HashMap::add(const std::string& key, const std::string& value)
{
// REHASH IF EXCEEDED LOAD FACTOR
double futureLoadFactor = double((sz + 1))/double(currentBucketCount);
if (futureLoadFactor > maximumLoadFactor)
{
std:: cout << "REHASHING KEYS....." << std::endl;
rehashKeys();
}
unsigned int index = getIndex(key);
if (!checkExists(Buckets_Array[index], key, value))
{
if (Buckets_Array[index] == nullptr)
{
Node* n = new Node;
n->key = key;
n->value = value;
n->next = nullptr;
Buckets_Array[index] = n;
}
else
{
addToEnd(Buckets_Array[index], key, value);
}
sz += 1;
}
}
Here are some helper member functions that I use:
void HashMap::fillArray(Node** nodeArray, int size)
{
for (int i = 0; i < size; i++)
{
nodeArray[i] = nullptr;
}
}
void HashMap::arrayCopy(Node** source, Node**& target, int arrysz)
{
for (int i = 0; i < arrysz; i++)
{
if (source[i] != nullptr)
{
Node* temp = source[i];
target[i] = temp;
}
else
{
target[i] = nullptr;
}
}
}
void HashMap::deleteLinkedList(Node* node)
{
if (node == nullptr)
{
return;
}
else if (node->next == nullptr)
{
delete node;
}
else
{
Node* next = node->next;
delete node;
deleteLinkedList(next);
}
}
void HashMap::addToEnd(Node*& node, std::string key, std::string value)
{
if ( node == nullptr )
{
Node* n = new Node;
n->key = key;
n->value = value;
n->next = nullptr;
node = n;
}
else
{
addToEnd(node->next, key, value);
}
}
this
HashMap HP;
HashMap HH;
HashMap HP.add("k", "v");
HH = HP;
gives me a "double free or corruption error".
however if I remove the HP.add part the program runs without errors
In arrayCopy you copy the pointer to an element from one hash map into the other. So, you have the same pointer in two maps, and consequently delete the same object twice.
You need to allocate a new element and copy the data from one object into the other.

Convert Infix to Prefix Notation

I have a task: make a program (C++), which converts "infix" notation to "prefix" and uses own "stack and queue" realizations.
But I get: "Critical error detected c0000374" and "Free Heap block modified at ... after it was freed" at last string of void main() { /*...*/ system("pause"); } or at last string of void toPrefix();
Can somebody help me and point out my mistake(s), please?
Source.cpp:
#include "iostream"
#include "fstream"
#include "string"
#include "Stack.h"
#include "Queue.h"
void toPrefix(const std::string& first)
{
int length = first.length();
char test = NULL, operand = NULL;
char *ptr = &test, *op_ptr = &operand;
Queue<char> List;
std::string Output;
Stack<char> OpStack;
for (int i = length - 1; i >= 0; i--) List.push(first[i]); //
while (List.getsize() != 0)
{
List.pop(ptr);
if (test >= 48 && test <= 57) //is it number?
{
Output.insert(Output.begin(), test);
}
if (test == '*' || test == '/' || test == '-' || test == '+')
{
OpStack.push(test);
}
if (test == ')')
{
OpStack.push(test);
}
if (test == '(')
{
OpStack.pop(op_ptr);
while (operand != ')')
{
Output.insert(Output.begin(), operand);
OpStack.pop(op_ptr);
}
}
}
}
void main()
{
const std::string& first = "9-(2+2)";
toPrefix(first);
system("pause");
}
Queue.h:
#include<iostream>
template <typename T>
class Queue
{
private:
struct queue_element
{
T value;
queue_element *next;
};
queue_element *first;
queue_element *last;
int size;
public:
Queue()
{
first = new(queue_element);
last = first;
first->value = -1;
first->next = 0;
size = 0;
}
Queue(T x)
{
first = new(queue_element);
last = first;
first->value = x;
first->next = 0;
size = 1;
}
int getsize()
{
return size;
}
void push(T value)
{
if (size == 0)
{
size++;
last = first;
first->value = value;
first->next = 0;
}
else
{
size++;
queue_element *temp = new(queue_element);
temp->next = 0;
temp->value = value;
last->next = temp;
last = temp;
}
}
void pop(T* ret)
{
if (size == 0)
{
std::cout << "Queue is empty!" << std::endl;
return;
}
queue_element *temp = first;
*ret = first->value;
first = first->next;
size--;
}
void peek(T *ret)
{
if (size == 0)
{
std::cout << "Queue is empty!" << std::endl;
return;
}
*ret = first->value;
}
};
Stack.h
#include <iostream>
template <typename T>
class Stack
{
private:
struct stack_element
{
T value;
stack_element *next;
};
stack_element *first;
stack_element *last;
int size;
public:
Stack()
{
last = new(stack_element);
first = last;
last->value = -1;
last->next = first;
size = 0;
}
Stack(T x)
{
last = new(stack_element);
first = last;
last->value = x;
last->next = 0;
size = 1;
}
int getsize()
{
return size;
}
void push(T value)
{
if (size == 0)
{
size++;
last->value = value;
last->next = first;
}
else
{
size++;
stack_element *temp = new(stack_element);
temp->next = last;
temp->value = value;
last = temp;
}
}
void pop(T* ret)
{
if (size == 0)
{
std::cout << "Stack is empty!" << std::endl;
return;
}
stack_element *temp = last;
*ret = last->value;
last = last->next;
delete temp;
size--;
}
void peek(T *ret)
{
if (size == 0)
{
std::cout << "Stack is empty!" << std::endl;
return;
}
*ret = first->value;
}
};
Well... I think that the problem is in you Stack class.
The string that you pass to toPrefix() is "9-(2+2)"
So the operation in you Stack<char> OpStack, defined in toPrefix(), are (if I understand well)
construction with default (no arguments) constructor
push() in correspondence of -
pop() in correspondence od (
push() in correspondence of +
push() in correspondence of )
Well, let's see what's is happening in it
1) after the construction with default constructor
we have
1a) size == 0
1b) first, last, first->next and last->next that are pointing to the same allocated memory area
1c) first->value == last->value == (char)-1
2) after the first call to push() (with -)
we have
2a) size == 1
2b) first, last, first->next and last->next that are pointing to the same allocated memory area
2c) first->value == last->value == '-'
3) after the first call to pop()
we have
3a) size == 0
3b) first, last, first->next and last->next that are pointing to the same DELETED memory area
3c) first->value == last->value == '-'
4) calling for the second time push() (with +)
4a) size is incremented
4b) is written (last->value = value;) in a DELETED area
4c) is written again (last->next = first;) in a DELETED area
I suppose that this can explain your problem.
p.s.: the "use a debugger" suggestion from Rambo Ramon and Sam Varshavchik is a good suggestion (IMHO)
p.s.2: sorry for my bad English

Linked list mistake at insertion

I'm trying to implement a simple doubly linked list with exposed nodes in C++ like this
(some methods omitted, should be pretty clear as to what they do):
template<typename T>
class Node
{
public:
Node(T _value)
{
m_Data = _value;
m_HasParent = false;
m_HasNext = false;
m_Parent = NULL;
m_Next = NULL;
}
void insertAfter(Node<T>* _item)
{
m_Next = _item;
m_HasNext = true;
_item->insertBefore(this);
}
void insertBefore(Node<T>* _item)
{
if(m_HasParent)
{
m_Parent->insertAfter(_item);
_item->insertAfter(this);
}
else
{
m_Parent = _item;
m_HasParent = true;
}
}
private:
T m_Data;
Node<T>* m_Parent;
Node<T>* m_Next;
bool m_HasParent;
bool m_HasNext;
};
template<typename T>
class LinkedList
{
public:
LinkedList()
{
m_Root = NULL;
m_HasRoot = false;
}
~LinkedList()
{
if(m_HasRoot)
{
delete m_Root;
}
}
void pushFront(T _value)
{
if(m_HasRoot)
{
Node<T>* node = new Node<T>(_value);
m_Root->insertBefore(node);
node->insertAfter(m_Root);
m_Root = node;
}
else
{
m_Root = new Node<T>(_value);
m_HasRoot = true;
}
}
void pushBack(T _value)
{
if(m_HasRoot)
{
Node<T>* last = m_Root;
while(true)
{
if(last->getHasNext())
{
last = last->getNext();
}
else
{
break;
}
}
Node<T>* node = new Node<T>(_value);
last->insertAfter(node);
return;
}
else
{
m_Root = new Node<T>(_value);
m_HasRoot = true;
}
}
T operator[](int _i)
{
Node<T>* last = m_Root;
for(int i = 0; i <= _i; i++)
{
if(last->getHasNext())
{
last = last->getNext();
}
else
{
break;
}
}
return last->getData();
}
private:
Node<T>* m_Root;
bool m_HasRoot;
};
However, when executing the following little test:
int main(int argc, char** argv)
{
LinkedList<int> l;
l.pushBack(0);
l.pushBack(1);
l.pushBack(2);
l.pushBack(3);
int count = l.getCount();
std::cout << "count: " << count << std::endl;
for(int i = 0; i < count; i++)
{
std::cout << "Value at [" << i << "]: " << l[i] << std::endl;
}
std::string s;
std::cin >> s;
return 0;
}
I expect to see the numbers 0, 1, 2, 3 printed out in this order, but this is what I get:
For some reason, the insertion to the back doesn't quite work. I find nothing fundamentally wrong with my code, can anybody spot the problem? This is on MinGW 5.1, 64bit, Windows 10 64bit. However, when executing this problem on runnable.com, everything seems to work just fine?? See this draft. Is this a bug in MinGW or some mistake on my part?
Edit 1
Now this is weird, sometimes it seems to work in runnable, and sometimes it yields the same result as on my local machine... I'm thoroughly confused.
Try changing the loop condition inside ListWidget::operator[] from i <= _i to i < _i. There should be no iteration for _i equal 0.
The sign is that you're starting printing from the second element i.e. 1 and printing the last element twice. You forgot about the root node.
Note that you're checking if a node has a succesor, but you aren't checking if the list is not empty (m_root != nullptr). Make this consistent - either remove all possible cases of UB or don't check anything.

returning something from a linked list

Can anybody tell me why my main program is printing out 9460301 instead of 350?
I'm just trying to insert a struct as a single item into a linked list. The struct has atrributes x and y. I then wish to print out the x attribute of the struct in my linked list. I have a huge program written out, and I tried stripping it down on this post just to what's neccessary to view for this new issue that has arisen for me.
My chunk struct and Linkedlist class are as follows:
struct chunk{
int x;
int y;
};
template <class T>
class linkedList
{
public:
class node
{
public:
///node class attributes
T mPayload;
node* mNext;
///constructor
node(T toucan):mPayload(toucan),mNext(NULL)
{}
///destructor
~node()
{
///cascading delete
if(mNext)
delete mNext;
}
///node class methods
};
///linkedList class attributes
node* mStart;
///constructor
linkedList():mStart(NULL)
{}
///destructor
~linkedList()
{
///initializes the cascading delete.
if(mStart)
delete mStart;
}
///linkedList class methods
T mReturnT(int indx)
{
if(!mStart)
{
T emptyList;
return emptyList;
}
else
{
node* cur;
for(int i = 0; i<indx+1; i++)
{
if(cur->mNext == NULL)
{
cout << "Indx out of range. Deleting last item." << endl;
break;
}
cur = cur->mNext;
}
return cur->mPayload;
}
}
void mInsertHelper(node* blah, T data)
{
if(blah->mNext != NULL)
mInsertHelper(blah->mNext, data);
else
{
blah->mNext = new node(data);
blah->mNext->mNext = NULL;
}
}
void mInsert(T data)
{
if(mStart == NULL)
{
mStart = new node(data);
//mStart->mPayload = data;
}
else
mInsertHelper(mStart, data);
}
T mPop()
{
///Removes the last item in the list,
///and returns it.
if(!mStart)
return NULL;
else
{
node* cur = mStart;
while(cur->mNext)
{
cur = cur->mNext;
}
T var = cur->mPayload;
delete cur;
return var;
}
}
int mSize()
{
if(!mStart)
return 0;
else
{
node* cur = mStart;
int counter = 1;
while(cur->mNext)
{
cur = cur->mNext;
counter++;
}
delete cur;
return counter;
}
}
};
And my main.cpp:
int main()
{
chunk head;
head.x = 350;
head.y = 600;
linkedList<chunk> p1Snake;
p1Snake.mInsert(head);
cout<<p1Snake.mReturnT(0).x<<endl;
}
You never initialise cur before iterating through it.
node* cur; // <-- UNINITIALISED!
for(int i = 0; i<indx+1; i++)
{
if(cur->mNext == NULL)
{
cout << "Indx out of range. Deleting last item." << endl;
break;
}
cur = cur->mNext;
}
return cur->mPayload;
That first line should be:
node* cur = mStart;
And I think you should use indx instead of indx+1 in that loop... Unless you were using a dummy-head scheme, which you're not.
The logic inside the loop for detecting out-of-bounds is a bit wrong, also. How about revamping the whole thing:
node* cur = mStart;
while( cur && indx > 0 ) {
cur = cur->mNext;
indx--;
}
if( !cur ) {
cout << "Indx out of range." << endl;
return T();
}
return cur->mPayload;