Stacked linked list, head is NULL pointer error w/ parenthesis

I am trying to code a calculator class that uses stacks to calculate a string. I have to implement the stack myself and I did so by using linked lists. Everything works fine until I use parenthesis. Whenever my code gets to the block of code where I deal with closing parenthesis I get this error:

Exception thrown: read access violation.
this->**head** was nullptr.

This is the code that gets the error in my linked list stack class
1
2
3
4
DataType top()
{
	return head->data;
}


This is the block of code that my calculator class calls when I get the error

1
2
3
4
5
6
7
8
9
10
11
else if (infix[i] == ')')
{
	while (operators.top() != '(')
	{
		int valueOne = operands.pop();
		int valueTwo = operands.pop();
		char op = operators.pop();
		operands.push(operate(valueTwo,valueOne,op));
	}
	operators.pop();
}


My pop() and push() functions in stack class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void push(DataType element)
{
	struct Node* newNode;
	newNode = new Node();
	newNode->data = element;
	newNode->next = head;
	head = newNode;
}

DataType pop()
{
	struct Node* temp;
	temp = head;
	DataType poppedValue = head->data;
	head = head->next;
	temp->next = NULL;
	free(temp);
	return poppedValue;
}


infix is a string received through std::getline. This block of code is inside a for loop that goes through the length of infix. If there is any other code that is needed please let me know. I just put the code that was used in the block of code that was giving the error to shorten things as much as possible.
Edit: Pretty sure this is actually wrong, ignore.

When you pop it the very last time, I think the function tries to deference the nullptr head for the value, but since it’s a nullptr, it throws an error. (Line 10, second block of code)
Last edited on
Topic archived. No new replies allowed.