Question

I am getting a seg fault with my huffman tree. I'm not sure if it's my...

I am getting a seg fault with my huffman tree. I'm not sure if it's my deconstructors but also getting some memory leaks. Can some one help me find my seg fault? It's in c++, thanks!

//#ifndef HUFFMAN_HPP
//#define HUFFMAN_HPP

#include<queue>
#include<vector>
#include<algorithm>
#include<iostream>
#include <string>
#include <iostream>
using namespace std;

class Node {
public:
    // constructor with left and right NULL nodes
    Node(char charTemp, int c) {
      ch = charTemp;
      count = c;
      left = NULL;
      right = NULL;
    };

// constuctor used while building the tree
Node(char charTemp, int c, Node *n1, Node *n2) {
    ch = charTemp;
    count = c;
    left = n1;
    right = n2;
};

/* ~Node() {
    delete left;
    delete right;
}*/

~Node() {
   if(left != NULL)
       delete left;
   if(right != NULL)
       delete right;
}

int count; // counting the frequency of the character in the string
char ch;
Node *left;
Node *right;
};

struct Comp { // compare used while building the minheap
bool operator()(const Node *a, const Node *b) {
    return a->count > b->count;
}
};
// our class
class Huffman {

private:
    std::priority_queue,Comp> pq; // using standard priority queue
std::vector a;
std::vector nodeCounter;
Node *root;

void incrementCount(char inc) {
    // internal function to calculate the frequency of the character in the string
    for (int i = 0; i < nodeCounter.size(); i++) {
      if (nodeCounter.at(i) -> ch == inc) {
        nodeCounter.at(i) -> count++; // incrementing the frequency of the character
        return;
      }
    }
}

public:
    // default constructor
    Huffman() {

    }
    // deconstructor
    ~Huffman() {
    // delete root;
      for (int i = 0; i < nodeCounter.size(); i++) {
        delete nodeCounter.at(i);
      }
      //delete root;
    }
    // to build the tree*/
void build_tree(std::string str) {

      for (int i = 0; i < str.length(); i++) {
        std::vector::iterator it = find(a.begin(), a.end(), str[i]); // finding the character in our previous built vector

        if (it == a.end()) // adding to the vector, if it was not added previously
        {
          a.push_back(str[i]);
          Node *n = new Node(str[i], 1);
          nodeCounter.push_back(n);

        } else { // incrementing the character frequency if it has already been added

          incrementCount(str[i]);
        }
      }

      for (int i = 0; i < nodeCounter.size(); i++) {
        pq.push(nodeCounter.at(i)); // adding the nodes to the priority queue which will help us to build the tree
      }

      while (pq.size() != 1) {

        Node *n1 = pq.top();
        pq.pop();
        Node *n2 = pq.top();
        pq.pop();

        Node *root = new Node('*', n1 -> count + n2 -> count, n1, n2);

        pq.push(root); // pushing the new node by combining the least frequent characters

      }

      root = pq.top(); // defining the root of the tree

    }
    // encode function
std::string encode(std::string code) {
      std::string ret = "";
      for (int i = 0; i < code.length(); i++) {
        ret = ret + encodeUtil(code[i], "", root); // finding the code of each character and combining them
      }

      return ret;
    }
    // recurisvely called in our encode function
std::string encodeUtil(char ch, std::string code, Node *m) {

    if (m == NULL) {
      return " ";
    }

    if (ch == m -> ch) {
      return code;
    }

    // calling the utility function for the left node
    std::string ret1 = encodeUtil(ch, code + "0", m -> left);

    if (ret1.compare(" ") != 0)
      return ret1;
       // calling function for right node
    std::string ret2 = encodeUtil(ch, code + "1", m -> right);
    if (ret2.compare(" ") != 0)
      return ret2;

    return " ";
}

std::string serialize() {
    // calling the serialize util function to make use of the root in a recursive way
    return serializeUtil(root, "");
}

// serializing util function
std::string serializeUtil(Node *root, std::string ret) {

    if (root == NULL) {
      return ret + "/"; // if the node is null then serializing it as '/''
    }

    ret = ret + root -> ch; // adding the character to the returning string
// ser left
    ret = serializeUtil(root -> left, ret);
// ser right
    ret = serializeUtil(root -> right, ret);

    return ret; // return string
}

};

int main() {
std::string input;

while (true) {

    // capturing the input from the user
    std::cout << "Input string: ";
    //std::cin >> input;
    std::getline (std::cin, input);
    if (input.compare("q") == 0)
      return 0;

    Huffman *h = new Huffman();

    // building the tree
    h->build_tree(input);

    std::cout << std::endl;
    // printing the encode of the string
    std::cout << h->encode(input) << std::endl;

    // serializing the tree
    std::cout << h->serialize() << std::endl;

    delete h;
}
}

//#endif

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Segmentation Fault is caused by trying to access memory that doesn't exist.

We need to double check all your pointers and make sure you are trying to access the information that you intended (address/value).

This might be the issue:

private:
    std::priority_queue,Comp> pq; // using standard priority queue

  std::priority_queue<HuffmanNode, std::vector<HuffmanNode>, Comp > pq;

You can also open the program in the debugger step through and find the source of the SEGFAULT. and the question and post it again.

Add a comment
Know the answer?
Add Answer to:
I am getting a seg fault with my huffman tree. I'm not sure if it's my...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I have almost done with this code to Implement Huffman Coding. However I have an error...

    I have almost done with this code to Implement Huffman Coding. However I have an error at the "Heap<Tree>". Could anyone help with solving this issue, really appreciated. Thank you!! import java.util.Scanner; public class HuffmanEncoding { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a text: "); String text = input.nextLine();    int[] counts = getCharacterFrequency(text); // Count frequency System.out.printf("%-15s%-15s%-15s%-15s\n", "ASCII Code", "Character", "Frequency", "Code");    Tree tree = getHuffmanTree(counts); // Create a Huffman tree String[]...

  • For this assignment, you will write a program to work with Huffman encoding. Huffman code is...

    For this assignment, you will write a program to work with Huffman encoding. Huffman code is an optimal prefix code, which means no code is the prefix of another code. Most of the code is included. You will need to extend the code to complete three additional methods. In particular, code to actually build the Huffman tree is provided. It uses a data file containing the frequency of occurrence of characters. You will write the following three methods in the...

  • I am having problems with the following assignment. It is done in the c language. The...

    I am having problems with the following assignment. It is done in the c language. The code is not reading the a.txt file. The instructions are in the picture below and so is my code. It should read the a.txt file and print. The red car hit the blue car and name how many times those words appeared. Can i please get some help. Thank you. MY CODE: #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { char *str; int...

  • You will construct a Huffman tree based on the given frequencies of 26 English alphabets in...

    You will construct a Huffman tree based on the given frequencies of 26 English alphabets in upper case plus the space character. An internal tree node class in HuffmanTree with necessary information is required. • You will not randomly switch left and right children when merger two trees. Instead, you will build a right-heavy tree according to the following strategies to select the right child. (1) The tree that is taller will be the right child, i.e., the height is...

  • Having code issues wth my C++ program. My program checks if two binary trees are similar...

    Having code issues wth my C++ program. My program checks if two binary trees are similar and if they're not they return false. My program is return true with different binary trees. Could use some help thanks #include <iostream> #include <string> using namespace std; //Struct of Nodes struct BinarySearchTree { int data; BinarySearchTree *left; BinarySearchTree *right; }; // Inserting nodes into BST BinarySearchTree* insert( BinarySearchTree* node, int val) { if (node == NULL) { BinarySearchTree *newNode = new BinarySearchTree(); newNode->data...

  • Hi there, I am working on a binary search tree code in c++. The program must...

    Hi there, I am working on a binary search tree code in c++. The program must store and update students' academic records, each node includes the student name, credits attempted, credits earned and GPA. I have made some progress with the code and written most of the functions in the .cpp file (already did the .h file) but i am struggling with what to put in the main and how to put an update part in the insert function. I...

  • I am stuck on a data structure problem, I am just going off of Geeks for...

    I am stuck on a data structure problem, I am just going off of Geeks for Geeks for help but I need to print 100 random numbers in the range of [1-200]. I can currently only print 5 numbers. Here is my code: #include <stdio.h> #include <stdlib.h> #include <limits.h> using namespace std; //binary tree has data & left and right child struct node{ int data; struct node *left; struct node *right; }; //create a new node struct node* newNode (int...

  • [c++]Please help complete the function of binary tree(contains string data) in a recursive way std::string findPath...

    [c++]Please help complete the function of binary tree(contains string data) in a recursive way std::string findPath (const std::string &s) const; // EFFECTS: Returns the path from the root node to the node with the string s. The path is encoded by a string only containing 'O' and 'l'. Each character, from left to right, shows whether going left (encoded by '0') or right (encoded by '1') from a node can lead to the target node. For example, we want to...

  • I'm having trouble getting my program to output this statement Enter a sentence: Test! There are...

    I'm having trouble getting my program to output this statement Enter a sentence: Test! There are 5 total characters. There are 1 vowel. There are 1 UPPERCASE letters. There are 3 lowercase letters. There are 1 other characters. Here's my code: #include<string.h> #include<stdio.h> #include<stdbool.h> int main() { char str[100]; int i; int vowels=0; int UC; int LC; int Others; int c; printf("Enter a sentence: \n"); gets(s); LC=countLC(&s); UC=countUC(&s); Others=countOthers(&s); printf("There are %d total characters.\n", ; for(i=0; i<strlen(str); i++){ if(isVowel(str[i])) vowels++;...

  • Return a method as an expression tree Hi guys. I need to return a method as...

    Return a method as an expression tree Hi guys. I need to return a method as an expression tree, it's currently returning null. public static ExpressionTree getExpressionTree(String expression) throws Exception {       char[] charArray = expression.toCharArray(); Node root = et.constructTree(charArray); System.out.println("infix expression is"); et.inorder(root); return et; } In the above method, et needs to have a value. -- Take a look at the complete class below. Kindly assist. ; public class ExpressionTree extends BinaryTree { private static final String DELIMITERS...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT