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.
Related
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.
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 3 years ago.
Improve this question
I am trying to create a singly linked list by inserting nodes at end, and despite having no errors I am unable to print my linked list. Please help me debug my code.
I tried online compiler on codechef and it shows SIGSEGV Runtime error. What is this supposed to mean?
struct node
{
int data;
struct node *next;
};
void insert(struct node *root,int data)
{
struct node *temp=new(struct node);
if(root==NULL)
{
temp->data=data;
temp->next=NULL;
}
root->next=temp;
temp->data=data;
temp->next=NULL;
}
void print(struct node *root)
{
struct node *temp;
temp=root;
while(temp!=NULL)
{
cout<<temp->data;
temp=temp->next;
}
}
int main()
{
struct node *root=NULL;
insert(root,1);
insert(root,2);
insert(root,3);
insert(root,4);
print(root);
return 0;
}
Please help me debug my code.
OK lets try a dry run.
Imagine your list is empty and you are inserting your first item. So root equals NULL and we call insert.
1) first thing
struct node *temp=new(struct node);
You allocate a new node, and set temp equal to it, so far so good.
2) next thing
if(root==NULL)
this is true as explained in the preamble, so we enter the if statement
3) next thing
temp->data=data;
temp->next=NULL;
these statements in the if body get executed and initialise the newly allocated object. It's not clear why you only want to do this when root == NULL, I would think you would want to initialise the newly allocated node always. But anyway, so far no errors.
4) next thing
root->next=temp;
Now here's the error. Ask yourself, what is the value of root at this point? When we started it was NULL, has anything changed it since? The answer of course is no, so you are dereferencing a NULL pointer. That explains the error.
You need to be able to look at the code you've written and see it for what it really does. The ability to dry run your code like I did above is a very valuable skill to have.
Unfortunately your code really is not very close to being correct. So I think the best thing would be to look at some working code and see how it operates and then start again.
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
Here is the Program
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
using namespace std;
struct node
{
int data;
node *next;
};
typedef node *list;
bool create(list header){
return header==NULL;
}
void insert_begining(list header,int item){
node*p;
p=new(node);
if (p=NULL)
{
return;
}
p->data=item;
p->next=header;
header=p;
}
void insert_end(list header,int item){
list p,q;
p=new(node);
p->data=item;
p->next=NULL;
if (header==NULL)
{
header=p;
}
else
{
q=header;
while(q->next!=NULL){
q=q->next;
}
q->next=p;
}
}
void print_list(list header){
node* p;
p=header;
while(p->next!=NULL){
cout<<p->data<<endl;
p=p->next;
}
}
int main(){
list header;
create(header);
insert_end(header,500);
insert_end(header,600);
insert_end(header,4);
insert_end(header,6);
print_list(header);
return 0;
}
i run the program and it shows
Process returned -1073741819 (0xC0000005) execution time : 6.720 s
i really don't know why.I think that the syntax is right
pleases check the program above and tell me what to do.
i am a beginner and i really don't know much about linked lists
First, you need to understand pass-by-value vs pass-by-reference. In the former case a copy of the var is passed and in the latter the actual var is passed. Ex:
void f1(int x) { // Pass by value
x = 1;
}
void f2(int& x) { // Pass by reference
x = 2;
}
int main() {
int y = 0;
f1(y);
// y is still 0
f2(y);
// y is now 2
}
In your program, you pass header by value:
void insert_begining(list header,int item){
// ....
header=p; // Only modifying the local var!
}
Some things I would do:
First, get rid of that typedef. This is C++ but you are not using classes, so I assume you haven't learned them yet. Instead, create a linked list struct:
struct node
{
int data;
node *next;
};
struct linked_list {
struct node *head;
linked_list() : head(nullptr) {} // ctor
};
No more typedef needed, and now you can easily pass by reference. Ex:
void insert_begining(linked_list& list, int item){
// removed for brevity
p->next = list.head;
list.head = p;
}
When you declare the header variable it is not initialized to NULL. In C++
variables are usually not initialized by the compiler upon declaration.
So when you make the call
insert_end(header, 500);
inside the function the else block is executed since header is not NULL but a garbage value. The culprit here is:
while(q->next!=NULL);
You cannot evaluate q->next since q points to a random memory location and hence the segfault. You need to assign to a variable before accessing it.
So in you main function add this:
list header = NULL;
Apart for this your might want to check BLUPIX's comments about other problems.
Also use nullptr instead of NULL if the compiler supports C++11
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I wrote a doubly linked list, and trying to add an append()(insert at the end)and len()(caculate the number of member in the list). I just don't understand why it doesn't work now. Here is the simplest code:
#include<iostream>
using namespace std;
class linkedList{
private:
struct node{
node* last;
node* next;
char* str;
};
node sentinel;
public:
linkedList();
~linkedList();
int len();
void append(char*);
};
linkedList::linkedList(){
sentinel.last=&sentinel;
sentinel.next=&sentinel;
sentinel.str="I am sentinel!!";
};
linkedList::~linkedList(){};
int linkedList::len(){
node* currentNode=&sentinel;
int count=0;
while ((*currentNode).next!=&sentinel){
count++;
currentNode=(*currentNode).next;
cout<<(*currentNode).str<<endl;
}
return count;
}
void linkedList::append(char* str){
node newNode;
newNode.str=str;
newNode.last=sentinel.last;
(*sentinel.last).next=&newNode;
sentinel.last=&newNode;
newNode.next=&sentinel;
}
int main(){
linkedList myList;
myList.append("Hello");
myList.append("World");
int length=myList.len();
cout<<length<<endl;
return 0;
}
What I am doing is just add two new nodes into the linked list, and caculate the total number of my nodes. it should return 2. but why it doesn't work?
newNode in your code below will go out of scope as soon as append is finished executing. Assigning it's memory address as a pointer to more global member is likely going to end in a segfault.
void linkedList::append(char* str){
node newNode;
newNode.str=str;
newNode.last=sentinel.last;
(*sentinel.last).next=&newNode;
sentinel.last=&newNode;
newNode.next=&sentinel;
}
Try allocating your node on the heap using new node, possibly using a shared_ptr to make memory management a bit simpler.
void linkedList::append(char* str){
node *newNode = new node;
newNode->str=str;
newNode->last=sentinel.last;
(*sentinel.last).next=newNode;
sentinel.last=newNode;
newNode->next=&sentinel;
}
With this approach, be sure to cleanup the nodes when destructing your linkedlist, via the delete operator on each node.
Alternatively, look into using shared_ptr's to a Node instead of raw pointers, which will always call delete when the linkedlist (and nobody else) is pointing to the node.
Use the new keyword to allocate a new node:
void linkedList::append(char* str){
node *newNode = new node();
newNode->str=str;
newNode->last=sentinel.last;
(*sentinel.last).next=newNode;
sentinel.last=newNode;
newNode->next=&sentinel;
}
This question already has answers here:
Passing a bool as a param. C++
(2 answers)
Closed 9 years ago.
Hello I want to write stack implementation, unfortunately something went wrong
CPP FILE
Node* head=0;
std::cout << "front insertion" << std::endl;
addBeg(head, 1);
std::cout<<head<<std::endl;
HEADER FILE
class Node
{public:
int value;
class Node *next_el;
Node(int value){ this->value=value;next_el=NULL;}
};
void addBeg(Node *head, int value){
head=new Node(value); //even that doesn't work!?
}
I would really like to know why "head" in main is still NULL value;
What do I do wrong?
You can fix this by changing the header, but it's underhanded:
void addBeg(Node * &head, int value){
head=new Node(value); // now it works
}
Both versions are invoked the same way in the code. Changing a function this way (to take an argument by reference instead of by value) could really trip up users, but I guess in this case it doesn't matter.
If you want to write your own linked list implementation (instead of just using, what is already there, like std::list), I recommend, that you take a look, first, about how linked lists work in C (not C++). A tutorial can be found here for example: http://www.codeproject.com/Articles/24684/How-to-create-Linked-list-using-C-C
Once you have it working in C, you can try to write a C++ "wrapper" around it as a class or template. Other than that, your question is not really precise enough to know, how exactly your list should work.
You are modifying pointer value only inside the addBeg() function, but you want to change value of the variable. Reminds me when i had similar problem and my teacher said "If it doesn't work, add asterisks"
So here it is:
class Node
{public:
int value;
class Node *next_el;
Node(int value){ this->value=value;next_el=NULL;}
};
void addBeg(Node **head, int value){
*head=new Node(value); //even that doesn't work!?
}
Node* head=0;
std::cout << "front insertion" << std::endl;
addBeg(&head, 1);//notice &
std::cout<<head<<std::endl;
The other solution would be to use reference as shown in #Beta's answer