The Reason Segmentation Fault in Linked List - linked-list

#include <iostream>
#include <string>
using namespace std;
struct Node{
Node *next;
int data;
};
int main(){
Node* head = NULL;
int data;
cin >> data;
Node*m = head;
while(data >0){
cout <<"enter a data";
cin >> data;
m -> data = data;
m -> next = m;
}
while(m -> next != NULL){
cout << m -> data << endl;
}
return 0;
}
Here is simple code that takes values when they are greater than 0 and make a linked list. after you enter a negative value, the while loop is terminated and prints the values.
However, the code gives me segmentation fault when it asks enter a data and after it takes the data. I could not solve it, what is the reason?

You get uninitialized pointer here. If you define link to next node as Node *next; you should initialise pointer with address to valid Node object before use.
And
Node* head = NULL;
...
Node*m = head;
...
m -> data = data; // NPE
as you can see, you trying to call member data of NULL object.
How to fix it:
Anways initialize pointer with valid address. For example:
int main(){
Node head;
head.next = NULL;
int data;
cout << "enter a data ";
cin >> data;
Node *prev = &head;
prev->data = data;
while(data >0){
Node *next = new Node();
cout <<"enter a data ";
cin >> data;
next->data = data;
next->next = NULL;
prev->next = next;
prev = next;
}
Node* m = &head;
while(m -> next ){
cout << m -> data << endl;
m = m->next;
}
return 0;
}

Related

Why my front view of the Linked list is not printing

So i was trying this question in which I have written the below code:-
#include <bits/stdc++.h>
using namespace std;
struct Node
{
char data;
struct Node* next;
};
struct Node *reverseList(struct Node *head)
{
Node *current = head;
Node *prev = NULL, *next = NULL;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
return head;
}
bool isPalindrome(struct Node* head)
{
Node* frontHead = head;
Node* reverseHead = reverseList(head);
Node* temp = reverseHead;
cout<<"back view"<<endl;
while(temp)
{
cout<<temp->data<<"->";
temp = temp ->next;
}
cout<<endl;
cout<<"front view"<<endl;
temp = frontHead;
while(temp)
{
cout<<temp->data<<"->";
temp = temp ->next;
}
cout<<endl;
bool flag = true;
// while(frontHead && reverseHead)
// {
// // cout<<frontHead->data<<"-->"<<reverseHead->data<<endl;
// if(frontHead->data !=reverseHead->data)
// {
// flag=false;
// break;
// }
// frontHead = frontHead->next;
// reverseHead = reverseHead->next;
// }
return flag;
}
void push(struct Node** head_ref, char new_data)
{
struct Node* new_node = (struct Node*)malloc(
sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct Node* ptr)
{
while (ptr != NULL)
{
cout << ptr->data << "->";
ptr = ptr->next;
}
cout << "NULL" << "\n";
}
// Driver code
int main()
{
struct Node* head = NULL;
char str[] = "abacba";
int i;
for (i = 0; i<strlen(str); i++)
push(&head, str[i]);
// printList(head);
isPalindrome(head) ? cout << "Is Palindrome" << "\n\n" : cout << "Not Palindrome" << "\n\n";
return 0;
}
When I try to print the node form the front as well as from the backward(after reversing the linked list I got this output:-
back view
a->b->a->c->b->a->
front view
a->
Is Palindrome
can Anyone tell me why i am not able to get the front view of the linked list .
Any help will be appreciated

Using fgets and strtok to read in data and create linked list

Need some help with reading in lines of data from a text file using the fgets and string tokenization commands, which will then be used to create a linked list. I've followed some examples I've found on Stack Overflow and other tutorial websites, but still cannot get the read function below to work properly in my program, it just causes it to crash. The data file has lines like this:
Zucchini, Squash, pound, 2.19, 45
Yellow, Squash, pound, 1.79, 15
Based on everything I've read, I believe I have the necessary code, but obviously I'm missing something. Also, I commented out one of the fields (the one for float price) as I'm not sure what to use to copy the float value from the data, as I cannot treat it as a string (the integer value right below it seems to let me get away with it in my compiler).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Struct for linked list node
struct produceItem
{
char produce[20];
char type[20];
char soldBy[20];
float price;
int quantityInStock;
struct produceItem *next;
};
// Function to read in data from file to
void read(struct produceItem **head)
{
struct produceItem *temp = NULL;
struct produceItem *right = NULL;
//char ch[3];
char line[50];
char *value;
FILE *data = fopen("RecitationFiveInput.txt", "r");
printf("Trying to open file RecitationFiveInput.txt\n");
if (data == NULL)
{
printf("Could not open file RecitationFiveInput.txt\n");
}
else
{
while(fgets(line, sizeof(line), data))
{
value = strtok(line, ", ");
strcpy(temp->produce, strdup(value));
value = strtok(NULL, ", ");
strcpy(temp->type, strdup(value));
value = strtok(NULL, ", ");
strcpy(temp->soldBy, strdup(value));
//value = strtok(NULL, ", ");
//strcpy(temp->price, strdup(value));
value = strtok(NULL, " \n");
strcpy(temp->quantityInStock, strdup(value));
temp->next = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
right = *head;
while(right->next != NULL)
{
right = right->next;
}
right->next = temp;
}
}
printf("Successfully opened file RecitationFiveInput.txt\n");
}
fclose(data);
return;
}
// Function to display the nodes of the linked list that contains the data from the data file
void display(struct produceItem *head)
{
int value = 1;
struct produceItem *temp = NULL;
temp = head;
printf("=============================================================================\n");
printf(" Item # Produce Type Sold By Price In Stock\n");
printf("=============================================================================\n");
if(temp == NULL)
{
return;
}
else
{
while(temp != NULL)
{
printf(" %d %s %s %s %lf %d\n", value, temp->produce, temp->type, temp->soldBy, temp->price, temp->quantityInStock);
value++;
temp = temp->next;
if(temp == NULL)
{
break;
}
}
}
return;
}
//Main function
int main()
{
int input = 0;
struct produceItem *head = NULL;
while(1)
{
printf("\nList Operations\n");
printf("=================\n");
printf("1. Stock Produce Department\n");
printf("2. Display Produce Inventory\n");
printf("3. Reverse Order of Produce Inventory\n");
printf("4. Export Produce Inventory\n");
printf("5. Exit Program\n");
printf("Enter your choice: ");
if(scanf("%d", &input) <= 0)
{
printf("Enter only an integer.\n");
exit(0);
}
else
{
switch(input)
{
case 1:
read(&head);
break;
case 2:
display(head);
break;
case 3:
//function
break;
case 4:
//function
break;
case 5:
printf("You have exited the program, Goodbye!\n");
return 0;
break;
default:
printf("Invalid option.\n");
}
}
}
return 0;
}
Never mind everyone, found the issue. The crashes were due to me not allocating memory for the temp pointer in the read me function.

how to use mouse event to get out loop in opencv using setmousecallback

I am using openCV's setmousecallback() function to break from the for while loop(of webcam video frames) as soon as user presses mouse right click..
But the program is getting hang instead. Someone can help me please..
Below is the code i am using, please pardon me for any compilation error
//mouse callback funtion
void getMouseLoc(int event, int xCor, int yCor, int flags, void* userInput)
{
Point3_<int> *mouseInputs = (Point3_<int>*)userInput;
mouseInputs->x= xCor;
mouseInputs->y = yCor;
mouseInputs->z = event;
}
// for loop
for( ; ; )
{
camera >> frame;
imshow("averageFrame", aver`enter code here`ageFrame);
setMouseCallback("averageFrame", getMouseLoc, &mouseInputs);
if( mouseInputs.z == EVENT_RBUTTONDOWN)
{
cout << "topmost cordinates of ROI selected by user" << endl;
count << mouseInputs.x << " and " << mouseInputs.y << endl;
break;
}
}
//mouse callback function
void getMouseLoc(int event, int xCor, int yCor, int flags, void* userInput)
{
Point3_<int> *mouseInputs = (Point3_<int>*)userInput;
mouseInputs->x= xCor;
mouseInputs->y = yCor;
mouseInputs->z = event;
}
// this does not have to be inside the loop, once is enough:
Point3_<int> mouseInputs;
setMouseCallback("averageFrame", getMouseLoc, &mouseInputs);
// for loop
for( ; ; )
{
camera >> frame;
imshow("averageFrame", aver`enter code here`ageFrame);
// you're missing a call to waitKey(), else your image won't get updated !!
int k = waitKey(40);
if ( k == 27 ) break; // esc pressed.
if( mouseInputs.z == EVENT_RBUTTONDOWN)
{
cout << "topmost cordinates of ROI selected by user" << endl;
count << mouseInputs.x << " and " << mouseInputs.y << endl;
break;
}
}

Save and read vector of vectors of Mat in OpenCV using Filestrage

I'd like to ask for help with reading and writing vector of vectors of Mats using opencv's filestorage.
I use this function to write:
Template<typename _Tp>inline void writeFileNodeList(FileStorage& fs, const string& name,const vector<_Tp>& items)
{
// typedefs
//typedef typename vector<_Tp>::const_iterator constVecIterator;
vector<Mat>::iterator it;
// write the elements in item to fs
fs << name << "[";
for (it = items.begin(); it != items.end(); ++it) {
fs << *it;
}
fs << "]";
}
and this to read:
template<typename _Tp>inline void readFileNodeList(const FileNode& fn, vector<_Tp>& result) {
if (fn.type() == FileNode::SEQ) {
//vector<Mat>::iterator it;
for (FileNodeIterator it = fn.begin(); it != fn.end();it++) {
_Tp item;
it >> item;
result.push_back(item);
}
}
}
Code for writing works badly and that one for reading is not possible to build.
I'm actually totally desparete, I have used all I can imagine. I have looked here for same sample codes but none of them didn't worked for me.
Thanks for help!!!
I have finally solved the problem by myself.
Here's the code:
void writeFileNodeList(FileStorage& fs, const string& name,vector<vector<Mat>> items)
{
int IDs=items.size();
// typedefs
fs << name << "{";
for (int i=0;i<IDs;i++)
{
stringstream ss;
string s;
string a;
a="ID-label";
ss << (i+1);
s = ss.str();
a+=s;
fs << a << "[";
for (int j=0;j<items[i].size();j++)
{
fs<<items[i][j];
}
fs <<"]";
}
fs << "}";
}
and here is the part for reading xml back
vector<vector<Mat>> readFileNodeList2(const FileNode& fn)
{
//cout <<fn.name() <<endl;
//cout <<fn.size() <<endl;
vector<vector<Mat>> output;
//cout << fn.isMap() << endl;
for (int ID=0;ID<fn.size();ID++)
{
stringstream ss;
string s;
string a;
a="ID-label";
ss << (ID+1);
s = ss.str();
a+=s;
FileNode temp_ID;
temp_ID=fn[a];
vector<Mat> one_person_patrerns;
readFileNodeList(temp_ID,one_person_patrerns);
output.push_back(one_person_patrerns);
}
return output;
}
template<typename _Tp>inline void readFileNodeList(const FileNode& fn,vector<_Tp>& result)
{
if (fn.type() == FileNode::SEQ) {
for (FileNodeIterator it = fn.begin(); it != fn.end();) {
_Tp item;
it >> item;
result.push_back(item);
}
}
}

removing two items from a stack and adding their values

I am writing a program that creates a stack using linked lists. I have all the functionality finished like push(), pop(), top(), etc.
The thing I am trying to figure out is how to remove two values from the stack, add them together, then push that into the stack. This is part of the assignment and we have to continue to do it until all the items are added together and only the sum remains in the stack.
Any help or tips would be appreciated!
EDIT: I solved my problem by just making another function!
Thank you to everyone who tried to help!
Here is my code:
#include <cstdlib>
#include <iostream>
using namespace std;
//Creating a node structure
struct node
{
int data;
struct node *next;
};
//class stack
class stack
{
struct node *top;
int size;
public:
stack()
{
top=NULL;
}
void push(); // insert an element
void pop(); // delete an element
void stackTop(); //retrive top item without removal
void stackSize(); //return the size of the stack
void isEmpty(); // return 1 if empty, 0 if not
void show(); // show the stack
};
//push items into a stack
void stack::push()
{
int value;
struct node *ptr;
cout << "\nEnter a number to insert: ";
cin >> value;
ptr = new node;
ptr->data = value;
ptr->next = NULL;
if(top != NULL)
{
ptr->next = top;
}
top = ptr;
cout<<"\nNew item is inserted to the stack!!!" << endl;
size ++;
}
//remove the top item
void stack::pop()
{
struct node *temp;
if(top == NULL)
{
cout<<"\nThe stack is empty!!!";
return;
}
temp = top;
top = top->next;
cout << "\nPoped value is " << temp->data << endl;
delete temp;
size--;
}
//retrive top value without removing it
void stack::stackTop()
{
struct node *temp;
if(top == NULL)
{
cout<<"\nThe stack is empty!!!";
return;
}
temp = top;
cout << "The top item is: " << temp->data << endl;
delete temp;
}
//show the stack
void stack::show()
{
struct node *ptr1 = top;
cout << "\nThe stack is:" << endl;
while(ptr1 != NULL)
{
cout << ptr1->data << " ->";
ptr1 = ptr1->next;
}
cout << "NULL" << endl;
}
//return if empty or not
void stack::isEmpty()
{
if(top == NULL)
{
cout<<"\nThe stack is empty!!!" << endl;
return;
}
else
{
cout << "\nThe stack is not empty!!!" << endl;
return;
}
}
//return the number of items in the stack
void stack::stackSize()
{
if(top == NULL)
{
cout<<"\nThe stack is empty!!!" << endl;
return;
}
else
{
cout << "\nThe stack has " << size << " items" << endl;
return;
}
}
//main function
int main()
{
stack s;
int choice;
while(1)
{
cout << "\nSTACK USING LINKED LIST" << endl << endl;
cout << "1:PUSH" << endl;
cout << "2:POP" << endl;
cout << "3:DISPLAY STACK" << endl;
cout << "4:RETRIVE TOP ITEM" << endl;
cout << "5:GET THE SIZE" << endl;
cout << "6:IS THE STACK EMPTY?" << endl;
cout << "7:EXIT" << endl;
cout << "Enter your choice(1-7): ";
cin >> choice;
switch(choice)
{
case 1:
s.push();
break;
case 2:
s.pop();
break;
case 3:
s.show();
break;
case 4:
s.stackTop();
break;
case 5:
s.stackSize();
break;
case 6:
s.isEmpty();
break;
case 7:
exit(0);
break;
default:
cout << "\nPlease enter correct choice(1-7)!!!" << endl;
break;
}
}
return 0;
}
Is the interface you have mandatory? Normally you would have your pop() operation return the value you just popped (rather than void), instead of just printing it. If you do that, your problem becomes simple, and you can just repeatedly use your algorithm to add them together.
As a matter of fact, pop(), stackTop(), stackSize(), and isEmpty() should probably all return their values. If the print statements aren't required within the functions, you could then just have your main program print the values it finds.

Resources