Why this code is giving segmentation fault in linked list intersection? - linked-list

// Online C++ compiler to run C++ program online
#include <bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *next;
Node(int val)
{
data=val;
next=NULL;
}
};
Node* findIntersection(Node* head1, Node* head2)
{
// Your Code Here
Node* h=nullptr;
Node* temp=h;
while(head2!=nullptr){
while(head1!=nullptr && head1->data<head2->data){
head1=head1->next;
}
cout<<head1->data<<endl;
if(head1->data==head2->data){
if(h==nullptr){
h=new Node(head1->data);
}
else{
temp->next=new Node(head1->data);
temp=temp->next;
}
}
head2=head2->next;
}
return h;
}
int main() {
// Write C++ code here
Node* l1= new Node(1);
l1->next=new Node(2);
l1->next->next=new Node(3);
l1->next->next->next=new Node(4);
l1->next->next->next->next=new Node(6);
Node* l2=new Node(2);
l1->next=new Node(4);
l1->next->next=new Node(6);
l1->next->next->next=new Node(8);
findIntersection(l1,l2);
return 0;
}
I tried to find intersection of two linked lists with elements in sorted order.
This is a question on GFG which can be found on link:
https://practice.geeksforgeeks.org/problems/intersection-of-two-sorted-linked-lists/1?page=1&category[]=Linked%20List&sortBy=difficulty

Why this code is giving segmentation fault in linked list intersection?
Because there are bugs in it. You'll benefit from learning how to debug small programs.
#include <bits/stdc++.h>
Unrelated to your crash, but you should never #include anything from the bits directory.
while(head2!=nullptr){
while(head1!=nullptr && head1->data<head2->data){
head1=head1->next;
}
// We could get here if head1==nullptr. The next line will crash.
cout<<head1->data<<endl;
...
else {
// temp was assigned NULL in the start, and now is being dereferenced.
temp->next=new Node(head1->data);
temp=temp->next;
}

Related

Set the number of linked list nodes C

I have a trace text file with several numbers written on it.
I want to set the number of output nodes to 100, 500, or 1000.
I want to measure the hit rate of the implemented FiFO page replacement algorithm using the given trace file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct list {
char *string;
struct list *next;
};
typedef struct list LIST;
int main(void) {
FILE *fp;
char line[128];
LIST *current, *head;
head = current = NULL;
fp = fopen("test.txt", "r");
while(fgets(line, sizeof(line), fp)){
LIST *node = malloc(sizeof(LIST));
node->string = strdup(line);//note : strdup is not standard function
node->next =NULL;
if(head == NULL){
current = head = node;
} else {
current = current->next = node;
}
}
fclose(fp);
//test print
for(current = head; current ; current=current->next){
printf("%s", current->string);
}
//need free for each node
return 0;
}

Why is it Segmentation fault every time?

This code gives error only in runtime and it's "Segmentation fault". How can this be tackled? I don't have any idea how to remove this error. Thanks in Advance!
#include <iostream>
#include <cstddef>
using namespace std;
class Node
{
private:
int data;
Node* nextNodeAddress;
public:
Node(): nextNodeAddress(NULL) {} // if next node is not used it must be null.
void setData(int); // this function sets data in the node
int retrieveData(); // this function retrieves the data from the node
};
void Node::setData(int data)
{ this->data=data; }
class List
{
private:
Node* headNode;
Node* currentNode;
int listSize;
public:
List();
void addNode(int);
void deleteNode(int);
};
List::List(): headNode(NULL),currentNode(NULL)
{
}
void List::addNode(int data)
{
Node* newNode = NULL;
newNode->setData(data);
newNode->setNextNode(NULL);
if(headNode==NULL)
headNode = newNode;
else
currentNode->setNextNode(newNode);
currentNode = newNode;
this->listSize++;
}
GCC with all warnings on throws this:
In member function ‘void Node::setData(int)’:
18:28: warning: declaration of ‘data’ shadows a member of 'this' [-Wshadow]
void Node::setData(int data)
Might be a good place to start checking.
Edit: The issue is discussed here, basically you're reusing the name data in both private int in the class definition and int data as the parameter for the method. How could it possibly decide which one is which when you do this->data = data?

Sorting char array in ascending order (with Link list)

I want to arrange my link list (which contains char arrays) in ascending order. This program should allow the user to input some names and then display them in ascending order. I have used the strncpy function. There are no compilation errors.But instead of names, the output gives some integers (perharps addresses). Please help me! I am new to C!
#include <stdio.h>
#include <malloc.h>
#include <string.h>
char name [10];
struct node
{
char nm [10];
struct node *next;
}*newnode, *prev, *temp, *display, *current, *list;
void createlist()
{
list=NULL;
};
void insert ()
{
newnode=(struct node*) malloc (sizeof (struct node));
printf("Enter the Name: ");
scanf("%s",&name);
strncpy(newnode->nm,name, 10);
newnode->next=NULL;
if (list==NULL)
{
list=newnode;
}
else if (name<list->nm)
{
newnode->next=list;
list=newnode;
}
else
{
temp=list;
int place;
place=0;
while (temp!=NULL && place ==0)
{
if (name>temp->nm)
{
prev=temp;
temp=temp->next;
}
else
{
place=1;
}
newnode->next=prev->next;
prev->next=newnode;
}
}
}
void displayname()
{
if (list==NULL)
printf("\n\nList is empty");
else
{
display=list;
while(display!=NULL)
{
printf("%d\n",display->nm);
display=display->next;
}
}
}
int main()
{
char choice;
choice=='y';
createlist();
do
{
insert ();
printf("Do you want to continue? ");
scanf("%s",&choice);
}while (choice='y'&& choice!='n');
displayname();
}
In the display function you have
printf("%d\n",display->nm);
The %d formatter outputs the argument as an integer. Use printf's %s formatter to get character arrays
printf("%s\n",display->nm);
You will still need to write the sorting code ... put the problem of outputtin numbers instead of text.

BCB 6.0 "raised exception class EAccessViolation with message 'Access violation at address'"

I'm newer to C++. I have written some code, but when i run it, there's always this:
raised exception class
EAccessViolation with message 'Access
violation at address'
i don't understand this. Would you like to help me solve it? It's important to me. Really, really thank you!
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <math.h>
#include <conio.h>
#define k 2
#define minoffset 0.5
using namespace std;
struct Point
{
double X;
double Y;
};
vector<Point> dataprocess();
void k_means(vector<Point> points,int N);
double getdistance(Point p1,Point p2)
{ double distance;
distance=sqrt((p1.X-p2.X)*(p1.X-p2.X)+(p1.Y-p2.Y)*(p1.Y-p2.Y));
return distance;
}
int getmindis(Point p,Point means[])
{
int i;
int c;
double dis=getdistance(p,means[0]);
for(i=1;i<k;i++)
{
double term=getdistance(p,means[i]);
if(term<dis)
{
c=i;
dis=term;
}
}
return c;
}
Point getmeans(vector<Point> points)
{
int i;
double sumX,sumY;
Point p;
int M=points.size();
for(i=0;i<M;i++)
{
sumX=points[i].X;
sumY=points[i].Y;
}
p.X=sumX/M;
p.Y=sumY/M;
return p;
}
int main()
{ int N;
vector<Point> stars;
stars=dataprocess();
N=stars.size();
cout<<"the size is:"<<N<<endl;
k_means(stars,N);
getch();
}
vector<Point> dataprocess()
{
int i;
int N;
double x,y;
vector<Point> points;
Point p;
string import_file;
cout<<"input the filename:"<<endl;
cin>>import_file;
ifstream infile(import_file.c_str());
if(!infile)
{
cout<<"read error!"<<endl;
}
else
{
while(infile>>x>>y)
{
p.X=x;
p.Y=y;
points.push_back(p);
}
}
N=points.size();
cout<<"output the file data:"<<endl;
for(i=0;i<N;i++)
{
cout<<"the point"<<i+1<<"is:X="<<points[i].X<<" Y="<<points[i].Y<<endl;
}
return points;
}
void k_means(vector<Point> points,int N)
{
int i;
int j;
int index;
vector<Point> clusters[k];
Point means[k];
Point newmeans[k];
double d,offset=0;
bool flag=1;
cout<<"there will be"<<k<<"clusters,input the original means:"<<endl;
for(i=0;i<k;i++)
{
cout<<"k"<<i+1<<":"<<endl;
cin>>means[i].X>>means[i].Y;
}
while(flag)
{
for(i=0;i<N;i++)
{
index=getmindis(points[i],means);
clusters[index].push_back(points[i]);
}
for(j=0;j<k;j++)
{
newmeans[j]=getmeans(clusters[j]);
offset=getdistance(newmeans[j],means[j]);
}
if(offset>d)
{
d=offset;
}
flag=(minoffset<d)?true:false;
for(i=0;i<k;i++)
{
means[i]=newmeans[i];
clusters[i].clear();
}
}
for(i=0;i<k;i++)
{
cout<<"N"<<i+1<<"="<<clusters[i].size()<<endl;
cout<<"the center of k"<<i+1<<"is:"<<means[i].X<<" "<<means[i].Y<< endl;
}
}
You surely have some algo errors in you code. It is difficult to deal with code without input data, that caused an error, but let's try:
First, lets look at function Point getmeans(vector<Point> points)
it is supposed to evaluate mean coordinates for cluster of points: if you pass an empty cluster to this function it will cause an error:
look here -
int M=points.size()
and here -
for(i=0;i<M;i++)
{
sumX=points[i].X;
sumY=points[i].Y;
}
if your cluster is empty than M will be zero and you loop will iterate 2^31 times (until 32 bit integer overflow) and each time you will try to read values of nonexistent vector items
So, You have to test if you vector is not empty before running main function loop and you have to decide which mean values should be assigned for zero cluster (May be you need an additional flag for empty cluster which will be checked before dealing with cluster's mean values)
Then lets examine function int getmindis(Point p,Point means[]) and, also, a place, where we call it:
index=getmindis(points[i],means); clusters[index].push_back(points[i]);
This function assings points to clusters. cluster number is ruled by c variable. If input point doesn't fit to any cluster, function will return uninitialized variable (holding any possible value) which. then is used as vector index of nonexisting element - possible access violation error
You probably have to initialize c to zero in declaration
Tell us when you will be ready with errors described above and also show us a sample input file (one which causes errors, if all datasets cause errors, show us the smallest one)

Modifying PC in jmp_buf to go to another function

For a user-lever thread library, I need to figure out jumping to a function by modifying PC value stored in jmp_buf.
This is what I have written:
jmp_buf env;
void print (void) {
printf("\nHello World!");
}
static int ptr_mangle(int p) {
unsigned int ret;
asm(" movl %1, %%eax;\n"
" xorl %%gs:0x18, %%eax;"
" roll $0x9, %%eax;"
" movl %%eax, %0;"
: "=r"(ret)
: "r"(p)
: "%eax"
);
return ret;
}
int main() {
int i = setjmp(env);
env[0].__jmpbuf[5] = ptr_mangle(print);
longjmp(env, 2);
return 0;
}
I am trying to modify PC in jmp_buf by setting it to the address of the function I am trying to jump to.
I am getting a segmentation fault.
I am unable to figure out what exactly needs to be done. Do I need to modify SP as well?
Any help would be very much appreciated.
What are you trying to do? Are you not checking for the return value of setjmp? I don't think you are doing this correctly. Have a look at the sample code below to see what would be the output be:
#include <stdio.h>
#include <setjmp.h>
#include <stdlib.h>
void subroutine(jmp_buf);
int main(void)
{
int value;
jmp_buf jumper;
value = setjmp(jumper);
if (value != 0)
{
printf("Longjmp with value %d\n", value);
exit(value);
}
printf("About to call subroutine ... \n");
subroutine(jumper);
return 0;
}
void subroutine(jmp_buf jumper)
{
longjmp(jumper,1);
}
The output would be:
About to call subroutine...
Longjmp with a value of 1.
Which begs the question - why are you trying to modify the IP? It sounds like you overwrote something or the code 'jumped' off into the woods and trampled something and came back with a hard landing i.e. segfault.
The variable env is specifically a struct, do not use an array subscript as you have done. I suspect that is why you got a segfault...
Hope this helps,
Best regards,
Tom.

Resources