Why am I getting a segmentation fault on my pointers? - c++

So I'm trying to write a function that returns a newly made Huffman tree, the function finds the two smallest frequencies in a list then removes them (remove_smallest) and then makes them the children of a new treeNode (root) and inserts it into the list again (in the style of Huffman trees) and does it all over until there is 1 element left in the list. My program seems to be crashing around the line just after the second call to the remove_smallest function. The remove_smallest function returns the smallest treeNode in the list It should keep going until there is one element left. Where am I going wrong? Any why am I getting a segmentation fault? As I mentioned it seems to be crashing right after the two calls to remove_smallest.
Am I dereferencing a pointer that's pointing at random memory? or setting an incorrect pointer to something?
Any help is appreciated. Thank you.
Code:
typedef TreeNode* Element;
typedef Frequency* TreeElement;
struct TreeNode {
TreeElement data; //stores a pointer to the data in this tree node
TreeNode *left; //reference to the left child tree
TreeNode *right; //reference to the right child tree
};
struct ListNode {
Element data; // stores a pointer to data in node
ListNode *next; // reference to next node in list
};
struct List {
ListNode *head; // reference to the first node in the list
int numElements; // the number of nodes in the list
};
struct HuffmanTree {
TreeNode *root;
};
struct FrequencyList {
List *freqs;
};
struct Frequency {
char data; // the character being represented
int count; // the number of occurrences of the character
};
HuffmanTree *createHuffmanTree(FrequencyList *frequencies) {
List * newList = new List;
newList = frequencies->freqs;
TreeNode * newTree1;
TreeNode * newTree2;
TreeNode * root = new TreeNode;
while (frequencies->freqs->numElements != 1) {
newTree1 = remove_smallest(frequencies); // removes and returns smallest treeNode from list
newTree2 = remove_smallest(frequencies);
root->data->count = newTree1->data->count + newTree2->data->count;
root->left = newTree1;
root->right = newTree2;
insert(newList, root); // inserts back into list
}
HuffmanTree * newHuffmanTree = new HuffmanTree;
newHuffmanTree->root = root;
return newHuffmanTree;
}

Segmentation Fault is caused by trying to access memory that doesn't exist. This is a very common error for people that are new to C/C++. I would double check all your pointers and make sure you are trying to access the information that you intended (address/value).

Related

Implementation of a list on a pointers

Let's make a list
struct node
{
node *next=nullptr;
int value=0;
};
Why do we start a list with a pointer node *head=nullptr, but not with an object node head? Is such an implementation faster than creating each node as an object whose fields are a value and a pointer to the next object? I don't understand how this implementation works.
I added function that adds new node to the front
void addFront(node *&head, int value)
{
node *nodeToAdd=new node;
nodeToAdd->value=value;
nodeToAdd->next=head;
head=nodeToAdd;
}
and another one that shows the list.
addFront(head1, 2);
showList(head1);
node *head2=new node;
addFront(head2, 2);
showList(head2);
Why first showList display 2 and the second one 2 0? The only difference is in head1 and head2 declaration.

HOW ARE Node a and Node* s different?

struct Node
{
int w;
Node* w1;
};
int main(){
Node a;
Node *s;
}
In above code what is difference between a and *s. How are they different.Also why we use Node *s while creating a LinkList.
THANK YOU!!!
Node a is an object. It allocates some space in memory.
Node *s1 - is pointer to object of type Node, but the object itself must be created with, for example, a new operator. Or we must explicitly take and address of the object with & operator. It is just a variable that holds an address. The size of this variable depends on platform (4 bytes on x86, 8 bytes on x86_64).
Each node of a Linked list stores a pointer to the next node. That is why we need a pointer here. Thus if you you have access to the node, you can travel to the next and to the end of the list.
Disclaimer: The given code is very basic and given for explanation only. This is not how you create linked list in real-life. Manually connecting nodes is not a great pattern. I would recommend you to learn more about basic language concepts like pointers, references, object lifetime.
// Node type definition
struct Node
{
int w;
Node* w1;
};
int main() {
// Separate nodes
Node n1;
Node n2;
Node n3;
// Now this is a linked list
n1.w1 = &n2;
n2.w1 = &n3;
n3.w1 = nullptr; // to mark the end
// Get pointer to n2 from n1
Node *n2_ptr = n1.w1;
Node *n3_ptr = n2.w1;
// Check if n3 is the last element
if (n3_ptr->w1 == nullptr) {
// this is the end of the list
}
// walk the list
Node *node = &n1;
while (node != nullptr) {
node->w *= 2; // do smth with data
node = node->w1; // go to the next node
}
return 0;
}

How to create nodes in c++?

Write a function to insert a node to the head of the linked list. The function takes two arguments: a pointer to the first node in the double linked list and a string value. It should create a new node with the given value to the head of the double linked list.
This is the question I need to answer. I'm not looking for the answer I'm just unsure how to create a node in C++.
That should be what you wanted.
struct node{
node * next;
std::string value;
};
node * addToTheFront(node * front, std::string value){
node * temp = new node;
temp->next = front;
temp->value = value;
return temp;
}

C++ Find node with highest value in unordered tree

I tried searching for this problem on stackoverflow but couldn't find it, so pardon me if it already existed.
So, what I wish to do is to create a function that traverses a tree and returns a pointer to the Node with the highest value. The Tree would be unordered and asymmetric, and will not have a fixed depth. Each node has a pointer to its Parent node, a list containing its Child nodes, and an integer named 'value'. And the tree would have a pointer to its root node, like this:
struct Node
{
private:
Node* parent;
list<Node> childs;
int value;
public:
// Getters, setters and constructors
}
struct Tree
{
private:
Node* root;
public:
// Getters, setters and constructors
}
And, as I stated before, I wish to make a function that traverses the entire tree, aka every single Node in the entire tree regardless of the depth, and returns a pointer to the node with the highest value. I assume it'll require recursion, but I can't figure out a way to do this.
Pardon me if my question seems dumb / stupid, but I really need help
You can use recursive method, which returns the pointer to the node with maximal value of current and child nodes:
struct Node
{
...
Node* getMaxNode()
{
Node* maxNode = this;
for (auto& child : this->childs) {
Node* childsMaxNode = child.getMaxNode();
if (childsMaxNode->getValue() > maxNode->getValue())
maxNode = childsMaxNode;
}
return maxNode;
}
}
If current node doesn't have child nodes, it will return pointer to the current node. So, in struct Tree you can implement something like this:
struct Tree
{
Node* getMax()
{
return this->root->getMaxNode();
}
}

Create and print a Linked list

#include <iostream>
using namespace std;
struct node
{
int num;
node * next;
};
//Create a list, if list is not empty have at least first middle and last node
void cList (node *);
//inserts a node
void iANode(node *);
//Inserts in order
void iIOrder(node *);
void main(){
int numM;
node *list, *current;
list = new node;
current = list;
cout<<"Input"<<endl;
cin>>numM;
//creates a list
void clist(node * record){
node * head = new node;
(*head).d1=0;
(*head).next =0;
return head;
}
//inserts a node
void iANode(node * record)
{
(*newnode).next = (*pred).next;
(*pred).next= new node;
++(*phead).counter;
}
//inserts in order
void iIOrder(node * new node, node*head){
node *pred = head;
int i = (*new node).d1;
node*succ=(*pred);
}
}
I am trying to create a linked list and sorting it after each user input.
Currently getting a whole lot of compile errors. Id appreciate if someone could help and point me in the right direction.
Thanks in advance.
Compile Errors:
Local function definitions are illegal for "cList" and "iANode"
";" missing after "node * record)"in cList
Expecting ")" after node in "void iIOrder(node * new node"
use struct node *next, instead of node *next. Same applies to *list and *current
some compilers does not accept void main(), try using int main()
put all function implementation outside main()
declare *current and *list as global variables (outside main())
C++ is case sensitive, cList is different from clist. fix cList implementation
not an error, but use -> operator: head->num = 0;
there is no field d1 in structure node (function cList and iIOrder). Use field num.
to nullify a pointer use NULL instead of 0
cList function is void, but you are returning a pointer, change return value
in iANode function you are using a lot of undeclared variables. You probably want to use *list, *current and *record.
There is a bunch of analythic errors, but you asked for syntax errors. Maybe you will find more errors later, try to fix theses first.