I am trying to implement polynomial addition using linked list. I have only coded a small part of it where i accept the input into first polynomial and while i was testing the code it kept throwing a segmentation fault error. I have sprinkled some random printf statements to try to debug the code.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
struct node{
struct node* next;
int coeff, power;
};
struct node* createNode(){
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->next = NULL;
return temp;
}
struct node* poly1,poly2,poly3;
void createList(struct node* head){
int ch=0;
struct node* temp;
struct node* newNode = createNode();
head=NULL;
temp=NULL;
while(ch!=-1){
printf("Enter coefficient and power");
scanf("%d",&newNode->coeff);
scanf("%d",&newNode->power);
if( head ==NULL){
printf("123123123");
temp = newNode;
head = newNode;
printf("bbbbbb");
}else{
printf("aaaaaaaa");
temp->next = newNode;
temp = newNode;
}
printf("Enter -1 to exit");
scanf("%d",&ch);
printf("9999");
}
printf("1");
}
void display(struct node* head)
{
struct node *temp;
temp=head;
if(temp==NULL)
printf("LL not present");
else
{
while(temp!=NULL)
{
printf("%dx^%d ",temp->coeff,temp->power);
temp=temp->next;
}
}
}
void main(){
printf("Enter the data for the first polynomial\n");
createList(poly1);
printf("%d",poly1->coeff);
display(poly1);
}
This is the output i am getting for it-
Enter the data for the first polynomial Enter coefficient and power3 2
123123123bbbbbbEnter -1 to exit9 9999Enter coefficient and power 1 1
1 1 aaaaaaaaEnter -1 to exit-1 Segmentation fault
Interestingly when i change the second last line of my while loop from
scanf("%d",&ch);
to ch=-1; the output that i get has none of the random printf i added to debug :
Enter the data for the first polynomial Enter coefficient and power3 2
Segmentation fault
I dont understand what the difference is between both of these cases. Also whats the issue with segmentation fault being thrown around?
As noted above you need to pass in the address of poly1, I made it a local rather than a global variable. Then you need to create a new node per loop iteration in createList(). Removed debugging output (use a macro and write something sensible in case you want to leave it in). Prefer for to while loops for iteration.
#include <stdio.h>
#include <stdlib.h>
struct node{
struct node* next;
int coeff, power;
};
struct node* createNode(){
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->next = NULL;
return temp;
}
void createList(struct node **head){
int ch;
*head = NULL;
do {
printf("Enter coefficient and power: ");
struct node* newNode = createNode();
if(scanf("%d %d",&newNode->coeff, &newNode->power) != 2) {
// TBD: free list
*head = NULL;
printf("scanf failed\n");
return;
}
if(!*head){
*head = newNode;
} else {
(*head)->next = newNode;
}
printf("Enter -1 to exit: ");
if(scanf("%d",&ch) != 1) {
// TBD: free list?
// *head = NULL;
printf("scanf failed\n");
return;
}
} while(ch!=-1);
}
void display(struct node *head)
{
if(!head) {
printf("LL not present");
return;
}
for(; head; head=head->next) {
printf("%dx^%d ", head->coeff, head->power);
}
printf("\n");
}
int main(void){
printf("Enter the data for the first polynomial\n");
struct node *poly1;
createList(&poly1);
display(poly1);
}
and example session:
Enter the data for the first polynomial
Enter coefficient and power: 1 2
Enter -1 to exit: 0
Enter coefficient and power: 3 4
Enter -1 to exit: -1
1x^2 3x^4
Consider reading a char instead of a int for the loop control (newline is continue, and 'q' could be quit). If you separate the UI from data structure manipulation then it will much easier to test your code (non-interactively). Write a function to free your list, and call that in the end. This will allow you to use a tool like valgrind to search for memory leaks.
For the first part of your question, I can't reproduce the issue. I changed the line scanf("%d", &ch); to ch = -1, and my output was: "123123123bbbbbbEnter -1 to exit99991", which does not match your output. Are you sure that your code compiled correctly?
For the second part of your question, the reason why you are getting a segment fault, is because you are not actually creating a new node for every polynomial. You only have one instance of a node, and in the while-loop, you constantly change the attributes of that node. In order for this to work, you have to create a new node for every polynomial, and insert that node into the list.
Some stylistic remarks:
It makes more sense to immediately assign a variable when you declare it. For example, in your code it happens a lot that you create a variable like this: int num;, and on the next line: num = 5;, for different datatypes and values. It makes more sense to immediately write: int num = 5;.
You declared poly1, poly2 and poly3, but you are only using poly1. You declared these variables globally, and then changed the contents of poly1 in a function. In order to optimally scope your variables, it makes more sense to write: struct Node *poly1 = createList();.
The code with these remarks implemented looks like this:
#include <stdio.h>
#include <stdlib.h>
struct Node {
struct Node* next;
int coeff;
int power;
};
struct Node* createNode(){
struct Node *head = malloc(sizeof(struct Node));
//error check if malloc failed.
if(head == NULL) {
exit(-1);
}
printf("Enter coefficient and power\n");
scanf("%d %d", &head->coeff, &head->power);
head->next = NULL;
return head;
}
struct Node *createList(){
int ch=0;
struct Node* head = NULL;
struct Node* temp = NULL;
while(ch != -1){
struct Node* newNode = createNode();
if(head == NULL) {
head = newNode;
temp = newNode;
} else {
temp->next = newNode;
temp = newNode;
}
printf("Enter -1 to exit");
scanf("%d",&ch);
}
return head;
}
void display(struct Node* head) {
while(head != NULL) {
printf("%dx^%d ",head->coeff,head->power);
head=head->next;
}
}
Related
This is my code for program to enter elements in beginning of a linked list and print the linked list which is working perfectly fine(i am getting correct output for it) -
#include <stdio.h>
#include <stdlib.h>
// this is insertion of a node in begining of a linked list
typedef struct Node
{
int data;
struct Node *next;
} n;
void Insert(struct Node** head,int x)
{
struct Node *temp = (n *)malloc(sizeof(struct Node));
temp->data = x;
temp->next = *head;
*head = temp;
}
void Print(struct Node* head)
{
struct Node *temp = head;
printf("The linked list is:");
while (temp != NULL)
{
printf("%d,", temp->data);
temp = temp->next;
}
printf("\n");
}
int main()
{
struct Node *head;
head = NULL;
int n, i, x;
printf("Enter how many numbers you want?\n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the number in the linkedlist\n");
scanf("%d", &x);
Insert(&head,x);
Print(head);
}
return 0;
}
for context the output is
Enter how many numbers you want?
6
Enter the number in the linkedlist
1
The linked list is:1,
Enter the number in the linkedlist
2
The linked list is:2,1,
Enter the number in the linkedlist
3
The linked list is:3,2,1,
Enter the number in the linkedlist
4
The linked list is:4,3,2,1,
Enter the number in the linkedlist
5
The linked list is:5,4,3,2,1,
Enter the number in the linkedlist
6
The linked list is:6,5,4,3,2,1,
now just to see if my concepts of pointers and pointer to structure is clear i modified the Print() function in code as while rest of he program remain same
#include <stdio.h>
#include <stdlib.h>
// this is insertion of a node in begining of a linked list
typedef struct Node
{
int data;
struct Node *next;
} n;
void Insert(struct Node** head,int x)
{
struct Node *temp = (n *)malloc(sizeof(struct Node));
temp->data = x;
temp->next = *head;
*head = temp;
}
void Print(struct Node* head)
{
struct Node *temp = head;
printf("The linked list is:");
// while (temp != NULL)
// {
// printf("%d,", temp->data);
// temp = temp->next;
// }
// printf("\n");
do{
printf("%d,", temp->data);
temp = temp->next;
}while((temp->next)!= NULL);
printf("\n");
}
int main()
{
struct Node *head;
head = NULL;
int n, i, x;
printf("Enter how many numbers you want?\n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the number in the linkedlist\n");
scanf("%d", &x);
Insert(&head,x);
Print(head);
}
Print(head);
return 0;
}
Now while i did the dry run where i am getting correct result ,the output i am getting is wrong,for context the output coming is
Enter how many numbers you want?
5
Enter the number in the linkedlist
1
The linked list is:1,
--------------------------------
Process exited after 5.156 seconds with return value 3221225477
Press any key to continue . . .
while i only made changes in Print() function why is'nt the compiler accepting the rest of the elements in linkedlist as input ? assuming there is some mistake in Print() function
Such function implementation
void Print(struct Node* head)
{
struct Node *temp = head;
printf("The linked list is:");
// while (temp != NULL)
// {
// printf("%d,", temp->data);
// temp = temp->next;
// }
// printf("\n");
do{
printf("%d,", temp->data);
temp = temp->next;
}while((temp->next)!= NULL);
printf("\n");
}
is incorrect.
Firstly it does not check whether the passed pointer is equal to NULL.
Secondly the condition in the do-while loop
}while((temp->next)!= NULL);
can invoke undefined behavior if after this statement within the loop
temp = temp->next;
the pointer temp again is equal to NULL (when the list contains one node). Because in this case a null pointer is used to access memory. Or in other case when the list contains more than one node the last node will not be outputted.
Program to create a singly link list but an Exception error (Segmentation fault) occurs while printing the data stored in the link list, although the program runs and show output
.
//Program to create a singly link list
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct node
{
int data;
struct node *next;
};
void main()
{
struct node *head, *newnode, *temp;
head = 0;
int choice = 1;
while (choice)
{
if(choice==1)
{
newnode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data ");
scanf("%d", &newnode->data);
newnode->next;
if (head == 0)
{
head = temp = newnode;
}
else
{
temp->next = newnode;
temp = newnode;
}
printf("Do you want to continue - Press 1 to continue and 0 to terminate ");
scanf("%d", &choice);
}
}
temp = head;
while (temp != 0)
{
printf("%d\t", temp->data);/*Here it show Exception error(Segmentation fault)*/
temp = temp->next;
}
getch();
}
There is a typo in this statement
newnode->next;
It seems you mean
newnode->next = NULL;
Pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )
Recently I learnt about doubly linked lists, and I have tried to write some code in C to implement them. The program below is supposed to receive integer inputs form the user and put them into a list with a maximum of ten integers. However, when I input the values and then print them, only the first and last values are output. How would one solve this issue?
Here is the code:
`#include <stdio.h>
#include <stdlib.h>
struct node {
struct node* prev;
int num;
struct node* next;
};
struct node *head,*p;
struct node* create_first_node(int x)
{
struct node *new = (struct node*)malloc(sizeof(struct node));
new->num=x;
new->prev=NULL;
new->next=NULL;
head=new;
p=head;
return new;
}
void add_node(int x)
{
struct node*new=(struct node*)malloc(sizeof(struct node));
new->num=x;
new->prev=p;
p->next=new;
(new->next)=NULL;
new=p;
}
void print_list(){
struct node *temp= head;
printf("\nThe list is:\n");
while (temp!=NULL)
{
printf("%d\t",temp->num);
temp=temp->next;
}
}
int main(){
int in[10];
int len,i;
head=NULL;
printf("How many nodes would you like?(Max=10) \n");
scanf("%d",&len);
for (i = 0; i < len; i++)
{
if (head == NULL && i==0)
{
printf("Enter Value for node %d\n",i+1);
scanf("%d",(in+i));
create_first_node(in[0]);
}
else
{
printf("Enter Value for node %d\n",i+1);
scanf("%d",(in+i));
add_node(in[i]);
}
}
print_list(head);
return 0;
}`
I wrote a linked list as
In [69]: !cat linked_list.cpp
//linked list: inserting a node at beginning
#include <stdlib.h>
#include <stdio.h>
struct Node {
int data;
struct Node *next;
};
void insert(int x);
void print();
struct Node *head; //global variable, can be accessed anywhere
int main() {
head = NULL; //empty list
printf("How many numbers?\n");
int n,i, x;
scanf("%d", &n);
for (i=0; i<n; i++) {
printf("Enter the number \n");
scanf("%d", &x);
insert(x);
print();
}
}
void insert(int x) {
Node *temp = (Node*) malloc(sizeof(struct Node));
(*temp).data = x;
(*temp).next = NULL;
head = temp;//insert to the head
if (head != NULL) (*temp).next = head;
head = temp;
}
void print() {
struct Node *temp = head;
printf("List is: ");
while(temp != NULL)
{
printf(" %d", (*temp).data);
temp = (*temp).next;
}
printf("\n");
}
Tried to run but get error report:
gcc linked_list.cpp
collect2: fatal error: /usr/local/bin/gnm returned 1 exit status
compilation terminated.
gcc provide few helpful hints.
What's the problem with my code?
When you have a pointer to a structure, as in the case of temp in your insert(), instead of doing stuff like
(*temp).data
you can use the arrow operator and do
temp->data
Since this is a C program, when declaring structure variables of the structure Node, you must use
struct Node var_name;
instead of
Node var_name;
And in C, it's better not to explicitly cast the return value of malloc().
See this.
So change the declaration of temp in insert() to
struct Node *temp = malloc(sizeof(struct Node));
in place of Node *temp = (Node*) malloc(sizeof(struct Node));.
And if you are trying to add new elements to the start of the linked list, you could change the insert() function to something like
void insert(int x) {
struct Node *temp = malloc(sizeof(struct Node));
temp->data = x;
temp->next = NULL;
if(head!=NULL)
{
temp->next = head;
}
head = temp;
}
With these changes, I got the following output:
How many numbers?
4
Enter the number
12
List is: 12
Enter the number
34
List is: 34 12
Enter the number
56
List is: 56 34 12
Enter the number
778
List is: 778 56 34 12
So I have a program that takes a data string and a number on the end that is it's position in the priority that it's to be printed out. I'm required to use linked list's and I've figured out how to do so with that, however the way this program is executed is at the end of the data strings and priority's the user is supposed to enter NONE and the program executes. The problem is that my check with strcmp is forcing the user to enter NONE twice to execute the program. I don't think I'm using the scanf for string and int values correctly and that's where my problem lies but I'm not sure.
Here's a correct sample input:
andk81739wewe 7
qweod125632ao 3
lenlc93012wasd 0
093deaeiao12 5
13jadacas291 3
...
NONE
Here's what actually has to be typed for the program to execute
andk81739wewe 7
qweod125632ao 3
lenlc93012wasd 0
093deaeiao12 5
13jadacas291 3
...
NONE
NONE
Any ideas as to why a second NONE has to be typed for the program to recognize that none has been typed?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LARGE 100
struct node
{
char data[LARGE];
int position;
struct node* next;
};
void sortedInsert(struct node** first, struct node* new_node)
{
struct node* current;
if (*first == NULL || (*first)->position <= new_node->position)
{
new_node->next = *first;
*first = new_node;
}
else
{
current = *first;
while (current->next!=NULL &&
current->next->position > new_node->position)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
struct node *newNode(char *new_data,int position)
{
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
strcpy(new_node->data,new_data);
new_node->position=position;
new_node->next = NULL;
return new_node;
}
void printList(struct node *head)
{
struct node *temp = head;
while(temp != NULL)
{
printf("%s \n", temp->data);
temp = temp->next;
}
}
int main(void) {
char job[LARGE],blank[1]={' '},*p,*q;
int number=0,x=0;
q=&blank[1];
struct node* first = NULL;
struct node *new_node = newNode(q,0);
printf("Please enter printing jobs\n");
while(x!=1){
if(strcmp(job,"NONE")==0){
x=1;
}
else{
scanf("%s", job);
scanf("%d", &number);
p=&job[0];
sortedInsert(&first, new_node);
new_node = newNode(p,number);
}
}
printf("Print Job in order from 9-0\n");
printList(first);
return 0;
}
Alternatively you may use following code segment. This one is more reduced and simplified approach.:
int main(void) {
char job[LARGE];
struct node *first = NULL;
struct node *new_node = NULL;
int number;
printf("Please enter printing jobs\n");
while(1)
{
scanf("%s", job);
if(!strcmp(job, "NONE"))
break;
scanf("%d", &number);
new_node = newNode(job, number);
sortedInsert(&first, new_node);
}
printf("Print Job in order from 9-0\n");
printList(first);
return 0;
}