C++ executable crashing [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am starting to create a binary tree. So far all I have added is an insert function and I believe it works fine. When I compile my application, header and implementation files together it produces a executable but with an error code above it about exception handler used.... When I go to run the executable it crashes. I don't understand why it is crashing, can someone please help! Thanks in advance.
The command line errors http://gyazo.com/7ca1e8fb1a66da39e927e9ba627d3f53
My application file called mainprogramming.cpp
#include <iostream>
#include <cstdlib>
#include "Header.h"
using namespace std;
int main()
{
int Rndnums[10] = {3, 99, 76, 49, 32, 9, 77, 64, 81, 24};
BinaryTree *tree = new BinaryTree();
for(int i = 0; i < 10; i++)
{
tree->insert(Rndnums[i]);
}
return 0;
}
My header file called Header.h
class BinaryTree
{
// Can only be accessed by the class itself
private:
struct node
{
// Data stored in this node of he tree
int data;
// The left branch of the tree
node *left;
// The right branch of the tree
node *right;
};
node *tree;
void insert(node *tree, int value);
// Can be accessed by all
public:
BinaryTree(){};
~BinaryTree();
void insert(int value);
};
My implementation file called implementation.cpp
#include <iostream>
#include <cstdlib>
#include "Header.h"
using namespace std;
// Inserts a value into the tree - notice **
void BinaryTree::insert(node *tree, int value)
{
// Check if nullptr. If so set new node
if (tree == nullptr)
{
// Create new node
tree = new node;
// Set new value
tree->data = value;
// Set branches to nullptr
tree->left = nullptr;
tree->right = nullptr;
}
// If the input value is less than the node in the tree
else if(value < tree->data)
{
insert(tree->left, value);
cout << "The value " << value << "has been added as a left child\n";
}
// If the input value is greater than the node in the tree
else if(value > tree->data)
{
insert(tree->right, value);
cout << "The value " << value << "has been added as a right child\n";
}
else
{
cout << "The value " << value << "can only be equal and must already exist in the tree\n";
}
}
void BinaryTree::insert(int value)
{
insert(this->tree, value);
cout << "It ran";
}

Your problem is in your insert call:
void BinaryTree::insert(node * leaf_head, int value)
{
...
}
You are copying the pointer address then trying to create an object in that memory space, and then modifying that object. It works fine when you change it to a reference to that pointer:
void BinaryTree::insert(node * & leaf_head, int value)
{
...
}
That way you are actually modifying the tree pointer within BinaryTree instead of a copy of it.

Related

C++ Binary Tree Path finding

I have a question regarding finding sum of a path of a binary int tree. This is for college so the requirements are as follows:
Take your code from Lab Sheet 3B (Binary Tree) for a binary tree of integers, and code a
method called hasPathSum() which given a binary tree and a sum, return true if the tree
has a root-to-leaf path such that adding up all the values along the path equals the given
sum. Return false if no such path can be found. The function prototype is
int hasPathSum(struct node* node, int sum)
Note: a "root-to-leaf path" is a sequence of nodes in a tree starting with the root node
and proceeding downward to a leaf (a node with no children). An empty tree contains
no root-to-leaf paths. So for example, the following tree has exactly four root-to-leaf
paths:
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
Root-to-leaf paths:
path 1: 5 4 11 7
path 2: 5 4 11 2
path 3: 5 8 13
path 4: 5 8 4 1
For this problem, we will be concerned with the sum of the values of such a path -- for
example, the sum of the values on the 5-4-11-7 path is 5 + 4 + 11 + 7 = 27.
I am having trouble with this. I have a binary tree, but the function hasPathSum() requirs to pass a node, not a tree. I canot figure out how to do this. I also don't know how to find the sum of a path from root to leaf (the hasPathSum body as well). This needs to be done recursively.
Any help is greatly appreciated.
Here is my node class:
#include <stdio.h>
#pragma once
struct TreeNode
{
public:
friend class BinaryTree;
TreeNode(int theData) : data(theData) {}
bool isLeaf();
private:
int data;
TreeNode *leftlink;
TreeNode *rightLink;
};
Here is the BinaryTree header file:
#include "TreeNode.h"
#include <stdio.h>
#include <algorithm>
#include <iostream>
using namespace std;
#pragma once
class BinaryTree
{
public:
BinaryTree();
void add(int toadd);
int height();
void inorderShow() const;
int hasPathSum(TreeNode * tree, int sum);
private:
void add(TreeNode *toAdd, TreeNode *& addHere);
int height(TreeNode *& root);
TreeNode *root;
void inorderShow(TreeNode *subTree) const;
};
And my BinaryTree cpp file:
#include "BinaryTree.h"
BinaryTree::BinaryTree()
{
}
void BinaryTree::add(int toAdd)
{
TreeNode *node = new TreeNode(toAdd);
add(node, root);
}
int BinaryTree::height()
{
return height(root);
}
void BinaryTree::add(TreeNode * toAdd, TreeNode *& addHere)
{
if (addHere == NULL)
addHere = toAdd;
else if (toAdd->data < addHere->data)
add(toAdd, addHere->leftlink);
else //toAdd->data >= addHere->data
add(toAdd, addHere->rightLink);
}
int BinaryTree::height(TreeNode *& n)
{
if (n == NULL)
return -1;
else
return 1 + max(height(n->leftlink), height(n->rightLink));
}
void BinaryTree::inorderShow(TreeNode * subTree) const
{
if (subTree != NULL)
{
inorderShow(subTree->leftlink);
cout << subTree->data << " ";
inorderShow(subTree->rightLink);
}
}
void BinaryTree::inorderShow() const
{
inorderShow(root);
}
int BinaryTree::hasPathSum(TreeNode * tree, int sum)
{
}
In the main.cpp, I have a tree as follows:
#include <iostream>
#include "BinaryTree.h"
#include "TreeNode.h"
using namespace std;
int main()
{
BinaryTree tree;
tree.add(5);
tree.add(6);
tree.add(3);
tree.add(4);
tree.add(9);
tree.add(11);
cout << "Height of the tree is: ";
cout << tree.height() << " ";
cout << "\nIn Order Show:" << endl;
tree.inorderShow();
cout << "Root to leaft path: " << endl;
cout << endl;
system("pause");
return 0;
}
Is someone could explain how can I accomplish this task and meet the requirements (aka not change the function hasPathSum() parameters) I would really appreciate that.
Seems to me the requirement is wrong (or maybe confused)
and code a method called hasPathSum() which given a binary tree and a
sum
So given that this is a method of the binary tree class the tree is passed implicitly so the only explicit parameter is the sum. So the method should be declared as
class BinaryTree
{
...
bool hasPathSum(int sum);
...
};
However the given signature is
int hasPathSum(struct node* node, int sum)
which has the wrong return type (int not bool) and an unexplained node parameter.
Here's how I would organise the solution, since it involves two methods, it maybe explains the confusion.
class BinaryTree
{
...
public:
bool hasPathSum(int sum) { return hasPathSumHelper(root, sum); }
...
private:
static bool hasPathSumHelper(TreeNode* node, int sum);
};
The public hasPathSum method has the signature implied by the problem description (the only signature that makes sense). It simply calls a private method hasPathSumHelper passing the root node and the sum, this gets round the problem of how you pass the private root node.
The hasPathSumHelper method is the recursive routine where the real work is done (left for you to implement). The public hasPathSum just kicks off the calculation by calling this method.
As you think about how to implement the hasPathSumHelper you might find it useful to add additional parameters (a sum_so_far parameter which, as you descend the tree, is the sum of all the nodes above you makes sense to me). That's OK because it's a private method, you can add what you like.

Linked-List only remembers most recent added object

I have an assignment that requires me to add objects into a linked list. The objects in question are Shapes.
My problem is that I can add objects to the list, but when I try to print them out, only the last added object is printed, the rest are just trash values.
My code looks like this:
Source.cpp:
#include "ShapeList.h"
#include <iostream>
using namespace std;
int main()
{
ShapeList list;
list.add(Rectangle(0,0,2,5));
list.print();
}
I am not allowed to change this code. For example, I am not allowed to send a pointer to the new rectangle, I'm supposed to "deep-copy" it. (I hope I'm using that word right.)
My ShapeList.h looks like this:
#ifndef SHAPELIST_H
#define SHAPELIST_H
#include "Shape.h"
#include "Rectangle.h"
class ShapeList
{
private:
Shape *conductor; //this will point to each node as it traverses the list
Shape *root; //the unchanging first node
public:
ShapeList();
void print();
void add(const Shape &s);
};
#endif
and the header looks like:
#include "ShapeList.h"
#include <iostream>
using namespace std;
ShapeList::ShapeList()
{
cout << "ShapeList created" << endl;
root = new Shape; //now root points to a node class
root->next = 0; //the node root points to has its next pointer set to equal a null pointer
conductor = root; //the conductor points to the first node
}
void ShapeList::add(const Shape &s)
{
cout << "Shapelist's add function called" << endl;
conductor->next = new Shape; //creates node at the end of the list
conductor = conductor->next; //goes to next node
Shape *pShape = s.clone(); //get a pointer to s
conductor->current = pShape; //points current to pShape point
conductor->next = 0; //prevents loops from going out of bounds
}
void ShapeList::print()
{
conductor = root; //the conductor points to the start of the linked list
if(conductor != 0)
{
while(conductor->next != 0)
{
conductor = conductor->next;
cout << conductor->current->width << endl;
}
//cout << conductor->current->width << endl;
}
}
The clone-function is overloaded in all shapes, in this case it's the rectangle's:
Rectangle * Rectangle::clone() const
{
cout << "Rectangle's clone function called" << endl;
Rectangle copiedRect(this);
Rectangle * pCopiedRect = &copiedRect;
return pCopiedRect;
}
Rectangle::Rectangle(const Rectangle *ref)
{
cout << "Rectangle's copy constructor called" << endl;
this->x = ref->x;
this->y = ref->y;
this->width = ref->width;
this->height = ref->height;
}
I know it's alot to read, and I'm sorry. I can remove stuff if it's not needed. I can also add more if you would like.
I have read Alex Allain's tutorial* about linked lists, and a couple of other articles. If anyone has another article, or something like that, to suggest I'm all ears.
http://www.cprogramming.com/tutorial/c/lesson15.html
Rectangle::clone() is invoking undefined behavior. You're returning the address of an automatic variable copiedRect, which falls of scope as soon as the function terminates.
Try this:
Rectangle * Rectangle::clone() const
{
cout << "Rectangle's clone function called" << endl;
return new Rectangle(*this);
}
And your copy-ctor should not even need to be implemented. All the members of Rectangle are trivially copyable. The default should work fine.
Note: I didn't really take the time to dissect your list insertion code, but the above is definitely a problem that needs to be addressed.

C++ Pointer target returning wrong value

I am a fairly experience C# programmer and trying to help out a friend with a C++ application that creates a Stack object. It has been well over 13 years since I've even seen C++ and I am having a damn fine time trying to recall the proper way to do this. It took me a bit to get up to speed on the Header/CPP distinction again, so there may be issues in there even. Here is my problem:
//Stack.h
#ifndef __STACK_INCLUDED__
#define __STACK_INCLUDED__
#include "Node.h"
class Stack
{
private:
/// Going to be the pointer to our top node
Node* m_topNode;
/// Running count of elements
int m_count;
public:
///Constructor
Stack();
///Allows us to retrieve the top value from the stack
/// and remove it from the stack
int Pop();
.
.
.
};
#endif
Below is the CPP that matches the header. I am doing in here JUST for debugging at the moment. I am also fully qualifying everything because I was not sure if that is causing issues with the pointers and loss of references.
//Stack.cpp
#include "stdafx.h"
#include "Stack.h"
#include <iostream>
Stack::Stack(){
m_count = 0;
m_topNode = NULL;
}
void Stack::Push(int Value){
std::cout << "\nPushing Value: ";
std::cout << Value;
std::cout << "\n";
if ( Stack::m_topNode )
{
std::cout << "TopNode Value: ";
std::cout << Stack::m_topNode->data;
std::cout << "\n";
}
std::cout << "\n";
Node newNode(Value, NULL, Stack::m_topNode);
Stack::m_topNode = &newNode;
Stack::m_count++;
}
The node class is a pretty simple entity. Just needs to store a value and the pointers on either side. I know I don't need to track in both directions for a Stack but I wanted to make this something that was easily changed to a Queue or similar construct.
//Node.h
#ifndef __NODE_INCLUDED__
#define __NODE_INCLUDED__
class Node
{
private:
public:
///Constructor allows us to specify all values.
/// In a stack I expect NextNode to be NULL
Node(int Value,Node* NextNode, Node* PreviousNode);
///Pointer to the next node
Node* Next;
///Pointer to the previous node
Node* Prev;
///Value to be stored
int data;
};
#endif
Very simple implementation:
//Node.cpp
#include "stdafx.h"
#include "Node.h"
Node::Node(int Value, Node* NextNode, Node* PreviousNode){
data = Value;
Next = NextNode;
Prev = PreviousNode;
}
My main is just about sending 2 values to the stack right now via Push and seeing what the values are printing:
#include "stdafx.h"
#include "Node.h"
#include "Stack.h"
using namespace std;
int main(){
Stack s = Stack();
for ( int i = 0; i < 2; i++ ){
s.Push(i * 10);
}
int blah;
cin >> blah; //Stall screen
return 0;
}
Here is the Output:
Pushing Value: 0
<blank line>
Pushing Value: 10
TopNode Value: -858993460
When I hit Node newNode(Value, NULL, Stack::m_topNode) in the debugger I can see it tracking the proper value in the current node, but m_topNode references a really odd value. I'm hoping it's very obvious that I'm doing something dumb as I don't remember this being this tricky when I did it years ago. Appreciate any help/insight to my incorrect manners.
Node newNode(Value, NULL, Stack::m_topNode);
Stack::m_topNode = &newNode;
Stack::m_count++;
This is your problem. You allocate the new node on the current stack, and then put the pointer into the linked list of nodes. This pointer will be invalid as soon as your stack frame returns, and all hell breaks lose. ;)
You need to allocate the node with new.
As stated by Norwæ, you need to allocate your newNode with "new" because if you dont, your newNode is static and will be out of scope at the end of the Push function.
You also need to call your private members without the "Stack::" as this is used in C++ only to access static class members and functions. replace "Stack::m_topNode" for "m_topNode" only, and Stack::m_count for m_count.
Here is a working Push function :
void Stack::Push(int Value){
std::cout << "\nPushing Value: ";
std::cout << Value;
std::cout << "\n";
if ( m_topNode )
{
std::cout << "TopNode Value: ";
std::cout << m_topNode->data;
std::cout << "\n";
}
std::cout << "\n";
Node * newNode = new Node(Value, NULL, m_topNode);
m_topNode = newNode;
m_count++;
}
This line:
std::cout << Stack::m_topNode->data;
happens before
Node newNode(Value, NULL, Stack::m_topNode);
Stack::m_topNode = &newNode;
Stack::m_count++;
So you're trying to print an uninitialized value. Reverse these and see what happens.

C++ Stack Push/Print Implementation

I'm trying to make a stack implementation in C++ but when I try to print the stack,
it just prints the first element instead of the whole stack.
I've tested it and I'm pretty sure that my Push function is right, but I'm not sure.
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
int main(){
StackElement *stack = new StackElement();
stack->data = 20;
stack->Push(30,stack);
stack->Push(40,stack);
stack->Print(stack);
}
#include <stdio.h>
#include <stdlib.h>
class StackElement{
public:
int data;
StackElement* next;
StackElement();
void StackElement::Push(int value, StackElement *oldElement);
void StackElement::Print(StackElement *element);
};
StackElement::StackElement(){
next = NULL;
}
void StackElement::Push(int value, StackElement *oldElement){
StackElement *newElement = new StackElement();
newElement->data = value;
printf("Element added to stack: %d\n", newElement->data);
oldElement->next = newElement;
}
void StackElement::Print(StackElement *element){
while(element->next != NULL){
printf("%d\n",element->data);
element = element->next;
}
}
Your code kept loosing the previous pushed element, leaking memory, as #Beta described.
I suggest comparing my code below to your code. You'll see, I've moved the handling of the stack elements outside, just to be able to keep track of the first element. Also, notice that there is no pointer in the main function. That is what we expect from a class.
Stack_element is a struct really as there's not much point in making the Stack_element itself encapsulated, it is just an implementation detail of Stack.
So here's my code derived from yours
#include<iostream>
struct Stack_element{
int data;
Stack_element*next;
};
class Stack{
private:
Stack_element*last_data, first_data;
public:
Stack():last_data(NULL), first_data(NULL){}
void push(int data);
void print() const;
};
void Stack::push(int data)
{
Stack_element*p=new Stack_element();
p->data=data;
p->next=NULL;
if(last_data)
last_data->next=p;
else // empty stack
first_data=p;
last_data=p;
}
void Stack::print()
{
for(Stack_element*p=first_data;p;p=p->next)
std::cout << p->data << std::endl; // ** Do not use printf in c++. Ever. **
}
and in the main function just call
Stack stack;
stack.push(30);
stack.push(40);
stack.print();
REMARK: For a C++ish print you might want to do an ostream& print(ostream& os) instead, where
std::ostream& Stack::print(std::ostream& os)
{
for(Stack_element*p=first_data;p;p=p->next)
os << p->data << std::endl;
return os;
}
just to be able to write std::cout << stack.print() << std::endl;. The benefit of this is that you can easily redirect to a file.
std::ofstream ofs("yourfile.txt");
ofs << stack.print() << std::endl; // prints to file instead of screen.
Suppose this much works as planned:
StackElement *stack = new StackElement();
stack->data = 20;
stack->Push(30,stack);
Now your data looks like [20]->[30]
Now you attempt
stack->Push(40,stack);
So the Push method creates a new StackElement, gives it the value 40, and sets Stack to point to it: [20]->[40]. Notice that [30] has been lost.
Then the Print function:
while(element->next != NULL){
printf("%d\n",element->data);
element = element->next;
}
If there is only one element (whose next is NULL), this function will quit and print nothing. If there are two, this function will print the data of the first, then quit. And there will never be more than two, as long as Push has that bug.

Class Tree vs Structure TreeNode

I have two separate programs, both dealing with evaluating expression trees with infix and postfix. One is based on structures while the other is based on classes. Now I am stuck on the part of my assignment(for the class version) that says to:
"Finish the implementation of the createExpressionTree() method"
and that
"Its very similar to your previous implementation, except that you will be using instances of the "class Tree" instead of instances of the "structure TreeNode"."
There is more to the both than what is below, but I think you can get the gist of things, so what I am asking is: How similar is the class implementation to the structure one? And can I just copy and paste the old code in that is shown below and make minor adjustments? I have been trying but am have issues with accessing private members and such.
So here is the class tree and my new version of createExpressionTree that is supposed to go with it
#ifndef TREE_H
#define TREE_H
#include <vector>
#include <stack>
#include <sstream>
#include <map>
# define TYPE_NUMBER 0
# define TYPE_VARIABLE 1
# define TYPE_OPERATOR 2
class Tree
{
public:
Tree(std::string input,Tree *leftSubTree=NULL,Tree *rightSubTree=NULL);
Tree(const Tree &inTree); //COPY CONSTRUCTOR
~Tree(); //DESTRUCTOR
int evaluate(std::map< std::string, int > ipMap); //EVALUATE THE EXPRESSION
void postOrderPrint();
void inOrderPrint();
private:
Tree *leftPtr;
std::string Op;
Tree *rightPtr;
int NodeType;
};
code associated with tree class
Tree::Tree(std::string input,Tree *leftSubTree,Tree *rightSubTree){
Op = input;
leftPtr = leftSubTree;
rightPtr = rightSubTree;
int num;
if (input == "+"|input == "-"|input == "*"|input == "/")
NodeType = TYPE_OPERATOR;
else if(std::istringstream(Op)>>num)
NodeType = TYPE_NUMBER;
else
NodeType = TYPE_VARIABLE;
}
// copy constructor
Tree::Tree(const Tree &inTree){
Op = inTree.Op;
NodeType = inTree.NodeType;
if (inTree.leftPtr == NULL){
leftPtr = NULL;
}
else {
leftPtr = new Tree(*(inTree.leftPtr));
}
if (inTree.rightPtr == NULL){
rightPtr = NULL;
}
else {
rightPtr = new Tree(*(inTree.rightPtr));
}
}
// tree destructor
Tree::~Tree(){
std::cout << "Tree destructor called" << std::endl;
if (leftPtr != NULL) {
delete(leftPtr);
leftPtr = NULL;
}
if (rightPtr != NULL) {
delete(rightPtr);
rightPtr = NULL;
}
}
#endif
New createExpressionTree that I would love some help with:
void arithmetic_expression::createExpressionTree(std::vector<std::string> expression)
{
std::stack <Tree> localStack;
std::string Op;
//Very similar to old implementation
}
And here is the previous implementation of the structure treeNode and the previous createExpressionTree that is completed
struct treeNode {
treeNode *leftPtr; /* pointer to left subtree */
std::string Op; /* integer data value */
treeNode *rightPtr; /* pointer to right subtree */
};
typedef struct treeNode TreeNode;
typedef TreeNode * TreeNodePtr;
previous createExpressionTree
void arithmetic_expression::createExpressionTree(std::vector<std::string> expression)
{
std::stack <TreeNodePtr> localStack;
std::string Op;
TreeNodePtr ptr;
for(int i=0; i<expression.size();i++)
{
Op = expression[i];
ptr = createNewTreeNode(Op);
if(char_is_operator(Op))
{
// adding element to right tree
if (localStack.empty())
{
std::cout<< "Invalid expression: tree not created " << std::endl;
topPtr = NULL;
return;
}
else
{
ptr->rightPtr = localStack.top();
localStack.pop();
}
// adding element to left tree
if (localStack.empty()) {
std::cout<< "Invalid expression: tree not created " << std::endl;
topPtr = NULL;
return;
}
else
{
ptr->leftPtr = localStack.top();
localStack.pop();
}
}
// pushing element to stack
localStack.push(ptr);
}
if (localStack.empty()) {
std::cout<< "Invalid expression: tree not created " << std::endl;
topPtr = NULL;
}
else
{
topPtr = localStack.top();
localStack.pop();
if (!localStack.empty()) {
std::cout<< "Invalid expression: tree not created " << std::endl;
topPtr = NULL;
}
}
}
I don't think there would be any difference between the class and structure version(the only difference between structs and classes is that classes have data private by default).
If he only wants you to change the word "struct" to "class", then you can access leftPtr/rightPtr by using the access modifier "public"
Example:
struct blah
{
int boringNumbers;
string boringStrings;
};
Is the same as:
class blah2
{
public:
int boringNumbers;
string boringStrings;
};
However, he might also want you to design your application to move more code into the class.
That would at the very least include moving functions such as char_is_operator into the class.
I doubt it, but he/she might also want you to create a hierarchy of nodes so you don't need to store data as generic strings.