Template variable assignment segment fault 11 [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 6 years ago.
Improve this question
I am currently working on a hash table project for school and i have run into an issue that i cant figure out. My professor provided us with classes that have functions that we need to implement and these functions make use of templates.
Anyway, in my insert function, i am running into an issue with setting a value of a node in the singly-linked list structure i am using to implement the hash table.
My problem is this:
void insert(U item1, U item2){ //For my project U is a string
Node<U>* temp = headPtr;
cout << item1 << endl; //Will print out the string no problem
//Assignment attempt
temp->SSN = item1; // causes a seg fault
temp->name = item2;
temp->next = NULL;
if(headPtr->next == NULL){
headPtr->next = temp;
size++;
}
else{
Node<U>* temp2 = headPtr;
while(temp2->next != NULL){
temp2 = temp2->next;
}
temp2->next = temp;
size++;
}
}
And it is quite frustrating because in previous assignments i have been able to use this insert function properly, the only reason it does not work i have concluded is because i must be missing something with templates that i have overlooked.
Also here is my node.h file:
#include <iostream>
using namespace std;
template <class T>
struct Node{
T SSN;
T name;
Node<T>* next;
};
I am trying to assign a string value to what SHOULD be a string value and should work to as far as my understanding goes but every time i run the program it gets to this point and there is just segment fault 11.

You have to replace
Node<U>* temp = headPtr;
with
Node<U>* temp = new Node<U>;

Related

Segmentation Fault with declared variables C++ [closed]

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 1 year ago.
Improve this question
I am trying to create a node class. The node class has two variables: an int, and a pointer to another node. Here are my node constructors. I found on another stack overflow that in order to allocate memory for values, you need to include a "new ... " phrase.
Node::Node() {
next = new Node;
}
Node::Node(int new_num) {
num = new_num;
next = new Node;
}
I am using a method called AssignArray which takes an array of ints and turns that into a linked list of nodes. Parts of it work, except when I try to use the setNext method on my node. The setNext method is just a regular setter.
void Node::setNext(Node* new_next) {
next = new_next;
}
Node* Node::AssignArray(int list[], int i, int size) {
if (i == size) {
return NULL;
}
else {
Node new_node(list[i]);
i++;
new_node.setNext(new_node.AssignArray(list, i , size));
return &new_node;
}
}
Here is my main function so far:
int main() {
int nums1[] = {1,2,3,4,5};
int nums2[] = {1,3,5,7,9};
Node node1 = Node();
int nums1_size = sizeof(nums1)/sizeof(nums1[0]);
node1.AssignArray(nums1, 0, nums1_size);
The main issue is that you're calling setNext with the return value from AssignArray, which you return as &new_node, which is a pointer to a local Node that you allocated on the stack. As soon as the function returns, the stack unwinds and that Node instance ceases to exist, leaving the pointer dangling.
At the very least you should be doing:
Node* new_node = new Node(list[i]);
...
return new_node;
But I also feel like we're missing some things here. It would be nice to see the definition of Node. And how is this constructor not producing a stack overflow?
Node::Node() {
next = new Node;
}
In the constructor you do new Node which will call this same constructor again... which will call the constructor again...
Hmm.
I think new node added on constructor while infinite loop through itself.
Node::Node() {
next = new Node;
}
It will be better to avoid this type of calling.

Making a linked list from a premade file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm trying to make a linked list from a premade file in c++. I'm struggling with the concept of taking the info if get from the file and using that to make the list. this is what i have so far.I also need to have the ability to insert and delete node from anywhere in the list.
struct node
{
string name;
int id;
float gpa;
node *next;
};
struct node* head;
void insertNodes(short id)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->id = id;
new_node->next = head;
head = new_node;
}
void deleteNode() {
if (head == NULL){
cout << "List is empty" << endl;
return;
}
cout << head->id << " is removed." << endl;
head = head ->next;
}
int main() {
head = NULL;
node entry;
fstream datafile;
datafile.open("datafile.dat", ios::in | ios::binary);
if (!datafile)
{
cout << "Error!!\n";
return 0;
}
datafile.read(reinterpret_cast<char *>(&entry), sizeof(entry));
}
if you are doing this in C++ you shouldn't be using malloc and free generally, and the struct keyword before every instance of the struc; those are C-ism's. You should probably be creating a class of your own to represent the list and using member functions instead of a global variables head, and using new and delete for dynamic instantiation and destruction of variables. There are cases for malloc still but this does not appear to be one them.
additionally your insert function only seems to take an input value and add it to the tail of the list; generally in a list you will want to take the insertion point and value unless you are calling the method 'pushback' or something along those lines.
Further unless you rewrite to make a List class of your own you have not done any object oriented programming currently, as you are just doing things procedurally and the only thing c++ about this code is the use of iostream and fstream.
Suggest that you make node a class as well. it's mostly semantic but will get you in the habit, and give node a constructor even if you don't want to make accessors.
beyond that you are asking for information without having attempted anything and your question is too broad.

Why did my C++mprogram stop working after being compiled? [closed]

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 6 years ago.
Improve this question
I'm a computer science student and have been coding with Java for the past year. Now I'm interested in learning C++. The first program that I wanted to code with C++ is an implementation of stack using linked list, which I have coded before using java. I pretty much have no idea what I'm doing and basically just writing what I thought was right until I got no compile error. So I finally did it, my program got no compile error, but when I ran it, a pop-up appeared saying that my 'Stack.exe has stopped working'
Here's my code:`
#include <iostream>
using namespace std;
class Stack;
class Node;
class Node
{
public:
string element;
Node *next;
Node(string, Node);
};
Node::Node(string element, Node next)
{
this -> element = element;
*(this -> next) = next;
}
class Stack
{
private:
Node *tos;
public:
Stack()
{
tos = NULL;
}
void push(string str)
{
tos = new Node(str, *tos);
}
string peek()
{
return tos->element;
}
string pop()
{
string temp = tos->element;
tos = (tos->next);
return temp;
}
};
int main(void)
{
Stack bob;
bob.push("Wow");
bob.push("Wiw");
cout << bob.peek();
return 0;
}
Can someone tell me what I did wrong? I did it like this because this was how I did it with Java.
Thank you :D
You're dereferencing null or undefined pointers in a couple places. First let's look at your Node constructor:
*(this -> next) = next;
Since next hasn't been defined yet, dereferencing it leads to undefined behavior. In practice, next will point to some random place in memory that you probably don't own, so writing to it will cause a program crash. Your Node constructor should take a pointer to Node as its second parameter instead of taking a Node by value:
Node::Node(string element, Node* next)
: element{element},
next{next}
{}
Note that I've also initialized Node's members instead of default-initializing them and then assigning to them in the constructor's body.
After fixing Node's constructor, you'll also need to fix Stack::push to pass a pointer instead of an object:
void push(string str)
{
tos = new Node(str, tos);
}
Note that even after fixing the crashing problem, you'll still leak memory when you pop from your Stack (or when a Stack is destroyed). You need to delete anything you new, or better yet use std::shared_ptr<Node> instead of raw Node*s.

Data structure in List [closed]

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
template <class type> class list
{
private:
struct element
{
type data;
element* prev;
element* next;
};
element* begin;
element* end;
int size;
public:
list()
{
begin = NULL;
end = NULL;
size = 0;
}
// data is copied twice. (why? how to solve it?)
void add_at_beginning(type data)
{
element* temp = new element;
temp->next = NULL;
temp->prev = NULL;
temp->data = data;
if (size == 0)
{
begin = end = temp;
size++;
}
else
{
temp->next = begin;
begin->prev = temp;
begin = temp;
size++;
}
}
};
In the function called void add_at_beginning(type data) there is a problem, I wrote the problem in a comment.
Namely I don't understand what it means to say that data is copied twice, and most importantly how can I solve this problem so that nobody says that in this code data is copied twice.
Your function void add_at_beginning(type data) takes its data argument by value, this means that when you call the function, a copy of data is made.
Then when you assign temp->data = data;, a second copy is made.
That's why you've been told that in your code data is copied twice.
You can avoid one of those copies by taking your data argument by reference. This may result in some performance improvements if your class is used with large types.
If you change your function's prototype to :
void add_at_beginning(const type& data)
Then only one copy will be made.

Why can't i print binary tree? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I created a class binary search tree.
but the problem is when i print the tree it crashes.
i think it can be an endless recursion in function print().
Here is my code
struct node{
node *l,*r;
int data;
};
class BinTree
{
private: node *root;
public:
BinTree(){ root=NULL; }
void add(int a){ add_node(a,root); };
void add_node(int a, node *rot)
{ node *curr; curr=rot;
if(curr==NULL)
{
curr=new node;
curr->data=a;
curr->l=NULL;
curr->r=NULL;
return;
}
if(a>=curr->data) curr=curr->r,add_node(a,curr);
if(a<curr->data) curr=curr->l,add_node(a,curr);
}
void print(){ inorder(root); }
void inorder(node *curr)
{
if(curr->l!=NULL) inorder(curr->l);
cout<<curr->data<<" ";
if(curr->r!=NULL) inorder(curr->r);
}
};
Can anyone help me?
In your add_node method, you never actually assign a value to the root. It should be something like this:
if(curr==NULL)
{
curr=new node;
curr->data=a;
curr->l=NULL;
curr->r=NULL;
root = curr;
return;
}
But, for the future, I have the same advice as Basile - use your compiler and your debugger to your advantange.
Your add_node is broken. If curr is NULL, it creates a new node but it never actually adds it to the existing tree. Thus all additions you make are effectively ignored and the tree stays empty.
The inorder function dereferences curr without checking whether it is NULL, and print calls it without checking whether root is NULL. Thus, your crash most likely is caused by tryin to print out an empty tree and then dereferencing a null pointer.
Learn how to use a debugger. Enable all warnings in the compiler.
On Linux, this means compile with g++ -Wall -g and debug with gdb