Okay this is making me sweat. I have a program that is compiling, but I am not receiving my desired output when I execute it on gcc, instead the output is Error. I am pretty sure my code and call for Print is at least correct. I can't find any error in my program that would mess up the output.
This is my code
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
node *Inserttail(node *head, int x){
node *temp = (node*)malloc(sizeof(node));
temp->data = x;
temp->next = NULL;
node *temp1 = head;
if(head==NULL)
return temp;
else if(head->next ==NULL){
head ->next = temp;
return head;
}
while(head->next != NULL)
head = head->next;
head->next = temp;
return temp1;
}
void Print(node *head){
if(head == NULL)
printf("Error");
while(head != NULL){
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
node *Deletemultiples(node *head, int k){
node *temp = head, *old = temp;
if(head == NULL)
return NULL;
if(head->data == 1)
head= head->next;
while(temp!=NULL){
if(temp->data %k ==0 && temp->data != k)
old->next = temp->next;
old=temp;
temp= temp->next;
}
return head;
}
void Freelist(node *head){
node *temp = head;
while(head != NULL){
head = head -> next;
free(temp);
temp = head;
}
}
int main(){
node *head = NULL;
int i;
for(i=1; i<=1000; i++)
head = Inserttail(head, i);
for(i=2; i<=32; i++){
head = Deletemultiples(head, i);
}
Print(head);
Freelist(head);
return 0;
}
Because of the if statement before the printf, I believe there is something wrong with head, I just can't find the issue.Any thoughts?
your code is correct. i run it under ubuntu 16.04 LTS with gcc 5.4.0 and
all things are OK.
Terminal output
Related
I am making a linked list program which utilizes several functions to simplify adding or removing nodes from the list. I believe that my logic is alright with allocating and adding a new node but I am still getting a seg fault. Could you look over my logic and explain what is causing the seg fault? I am very inexperienced with linked lists. Thank you!
This is my function declarations
#define SIMPLELL_H
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}node_t;
node_t* head;
void printList();
void append(int num);
void addFront(int num);
void deleteList();
void removeNode(int num);
int length();
#endif
This is the function definitions
void printList(){
// declare temp to traverse the LL and print each value
node_t *temporary = head;
while(temporary != NULL){
printf("%d, ", temporary->data);
temporary = temporary->next;
}
if (head == NULL){
printf("This list is empty.\n");
}
}
void append(int num){
//declare temporary pointer to traverse LL
node_t *tmp = head;
node_t *prev = NULL;
//malloc the new node
node_t *new = malloc(sizeof(node_t));
if(head == NULL){
//initialize the new node
new->data = num;
new->next = NULL;
head->next = new;
}
else{
//initialize the new node
new->data = num;
new->next = NULL;
//loop to traverse to the last value in the node
while(tmp != NULL){
prev = tmp;
tmp = tmp->next;
}
prev->next = new;
}
}
void addFront(int num){
//allocate memory for new node and allocate local variable equal to head
node_t *new = malloc(sizeof(node_t));
new->data = num;
new->next = head;
head = new;
}
void deleteList(){
node_t *tmp = head;
node_t *prev = NULL;
while(tmp != NULL){
prev = tmp;
tmp = tmp->next
free(prev);
}
}
void removeNode(int num){
//temp is used to traverse the ll until I find the node with the value
//then the previous value is linked to the next value removing the middle value.
node_t *temp = head;
node_t *prev = NULL;
if(head == NULL){
printf("List is not initialized\n");
return;
}
while(temp->data != num){
prev = temp;
temp = temp->next;
if (temp->data == num){
prev->next = temp->next;
free(prev);
}
else{
printf("Value is not in the list\n");
return;
}
}
int length(){
int length = 0;
node_t *temp = head;
while (temp != NULL){
length += 1;
temp = temp->next;
}
return length;
}
This is the driver function which I should not have to change
#include "SimpleLL.h"
#include "SimpleLL.c"
int main()
{
/*head is a global variable*/
head = NULL;
int size =0;
removeNode(1);
append(2);
append(3);
addFront(1);
append(4);
printList();
size = length();
printf("size now %d\n",size);
removeNode(8);
printList();
removeNode(1);
printList();
removeNode(4);
printList();
deleteList();
printList();
size = length();
printf("size after deletion %d\n",size);
return 0;
}
removeNode contains no test for reaching the end of the list. So if the value is not found in the list, it will dereference the NULL pointer at the end and crash.
This will be the case in the very first test, which attempts to remove a node when the list is empty, as well as for removeNode(8).
Your removeNode function also needs to free() the node it removed. Currently it is freeing the node that came after the one removed, which is still in the list and will cause undefined behavior when you access it later.
I found this on Internet to reverse a list using recursion and applied it in codeblocks but the output only reverse prints last two Insert call from main function. It skips the first three Insert calls. Why? I did search for this problem here but I failed to understand them as I'm a beginner. Kindly help
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node * head;
struct Node* Insert (struct Node* head, int data)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
if(head == NULL)
{
head = temp;
return;
}
struct Node* temp2 = head;
while(temp2->next != NULL)
{
temp2 = temp2->next;
}
temp2->next = temp;
}
void reversePrint(struct Node* head)
{
if(head == NULL)
{
printf("\n");
return;
}
reversePrint(head->next);
printf(" %d ", head->data);
return;
}
int main()
{
struct Node* head = NULL;
head = Insert(head,2);
head = Insert(head,7);
head = Insert(head,3);
head = Insert(head,1);
head = Insert(head,4);
reversePrint(head);
return 0;
}
O/P : 4 1
NOTES:
Don't cast the return of value of malloc
You declared two *head and confused yourself
No need to pass pointer to function and return pointer when you have head declared as global. Which is not a good idea but I followed your code.
Code:
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node * head;
void Insert (int data)
{
struct Node* temp = malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
if(head == NULL)
{
head = temp;
return;
}
struct Node* temp2 = head;
while(temp2->next != NULL)
{
temp2 = temp2->next;
}
temp2->next = temp;
}
void reversePrint(struct Node* head)
{
if(head == NULL)
{
printf("\n");
return;
}
reversePrint(head->next);
printf(" %d ", head->data);
return;
}
int main()
{
Insert(2);
Insert(7);
Insert(3);
Insert(1);
Insert(4);
reversePrint(head);
return 0;
}
OUTPUT:
4 1 3 7 2
I've been messing aroung with the linked list implementation in C and got stuck at this problem: why is it giving me expected expression before 'Node' in the following lines?:
Node *newNode1= malloc(sizeOf(Node));
Node *newNode2= malloc(sizeOf(Node));
Node *newNode3= malloc(sizeOf(Node));
Node *newNode4= malloc(sizeOf(Node));
I've never seen such problems in C before. What went wrong ?
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node_{
int data;
struct Node_ *next;
}Node;
void insertNodeBegin(Node **head, Node *newNode){
if((*head)==NULL){
(*head)->next = NULL;
*head = newNode;
}
else{
newNode->next = (*head)->next;
(*head)->next = newNode;
}
}
void printList(Node *head){
Node *current = head;
while(current != NULL){
printf("%d ", current->data);
current = current->next;
}
}
int main()
{
Node *head = NULL;
Node *newNode1= malloc(sizeOf(Node));
newNode1->data = 12;
Node *newNode2 = malloc(sizeOf(Node));
newNode2->data = 16;
Node *newNode3 = malloc(sizeOf(Node));
newNode3->data = 55;
Node *newNode4 = malloc(sizeOf(Node));
newNode4->data = 8;
insertNodeBegin(&head, newNode1);
insertNodeBegin(&head, newNode2);
insertNodeBegin(&head, newNode3);
insertNodeBegin(&head, newNode4);
printList(head);
return 0;
}
sizeOf(Node) should be sizeof(Node), note the small o. After all this is C, not Java. :)
In short reorder if commands inside insertNodeBegin()
if(*head == NULL){
*head = newNode;
(*head)->next = NULL;
}
Because in first execution of program head points to NULL and for it we haven't any allocated memory. As head in first execution not points to a Node location using head -> next not valid and cause segmentation fault in run time.
In node creation with malloc() we must check is memory allocation successful or not. for that i use createNode() function.
We check if memory allocation for Node is OK then add that Node to list. And finally Use void as main(void) argument.
After these change your code becomes
Code
#include <stdio.h>
#include <stdlib.h>
typedef struct Node_{
int data;
struct Node_ *next;
}Node;
void insertNodeBegin(Node **head, Node *newNode){
if(*head == NULL){
*head = newNode;
(*head)->next = NULL;
}
else{
newNode->next = (*head)->next;
(*head)->next = newNode;
}
}
void printList(Node *head){
Node *current = head;
while(current != NULL){
printf("%d ", current->data);
current = current->next;
}
}
int createNode(Node **node, int value){
*node = malloc(sizeof(Node));
if(*node){
(*node)->data = value;
return 1;
}else{
fprintf(stdout, "%s", "can't allocate ...\n");
return 0;
}
}
int main(void)
{
Node *head = NULL;
Node *newNode1;
Node *newNode2;
Node *newNode3;
Node *newNode4;
if(createNode(&newNode1, 12)) {
insertNodeBegin(&head, newNode1);
}
if(createNode(&newNode2, 16)) {
insertNodeBegin(&head, newNode2);
}
if(createNode(&newNode3, 55)) {
insertNodeBegin(&head, newNode3);
}
if(createNode(&newNode4, 8)) {
insertNodeBegin(&head, newNode4);
}
printList(head);
return 0;
}
I have been trying to implement the delete function for singly linked list.
My implementation is as follow.
typedef struct singly_linked_list{
int data;
struct singly_linked_list *next;
}sll;
Function to delete first node is as follow:
void delete_node_from_front(sll ** head){
sll ** temp;
*temp = *head;
(*head) = (*head)->next;
(*temp)->next = NULL;
free_node(temp);
}
Another function from where I am calling this function:
void delete_node_from_given_pos(sll ** head, int pos){
int i = 1;
sll * temp;
sll * prev;
temp = *head;
prev = *head;
if(pos == 1){
delete_node_from_front(head);
}
else{
while(temp != NULL && i < pos){
i++;
prev = temp;
temp = temp->next;
}
if(temp != NULL){
prev->next = temp->next;
temp->next = NULL;
free_node(&temp);
}
else{
printf("Node with given position is not present");
}
}
}
This implementation is giving me segmentation fault.
But If I replace the function call delete_node_from_front() in the imlementation of delete_node_from_given_pos() by the below code
(*head) = (*head)->next;
temp->next = NULL;
free_node(&temp);
program runs perfectly. The way I am calling the fucntion:
sll * head;
head = NULL;
int arr[_SIZE]=_ELEMENT;
create_list(&head, arr, _SIZE);
delete_node_from_given_pos(&head, 1);
print_list(head);
Implementation of print_list function
void print_list(sll * head){
int i = 0;
while(head != NULL){
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
implementation of free_node function:
void free_node(sll ** head){
free(*head);
}
What could be the possible reason for this behavior?
I have been trying to fix this code since morning but could get it done. So, finally i need some help in figuring out the error. The code compiles with no error but when i run it from terminal i get an error saying "segmetation error: 11"
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
};
struct Node *head;
void Insert(int data);
void Print();
int main()
{
head = NULL; //list is empty
Insert(3);
Insert(5);
Insert(2);
Insert(8);
Print();
return 0;
}
void Insert(int data)
{
struct Node *temp = malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
struct Node *temp1 = head;
while(temp1 != NULL)
{
temp1= temp1->next;
}
temp1->next = temp;
}
void Print()
{
struct Node *temp =head;
while(temp != NULL)
{
temp = temp->next;
printf("%d", temp->data);
}
}
You never set head to anything other than NULL.
(Even if you fix the above) temp1 is guaranteed to be NULL by the time you get to temp1->next = temp;.
P.S. I don't think it's such a great practice to call you variables temp, temp1 etc. From those names it is impossible to tell what their supposed function is.
Usually single linked lists have an inserting operation that inserts data at the beginning of the list. Nevertheless your function insert can look the following way
void Insert( int data )
{
struct Node *temp = malloc(sizeof( struct Node ) );
temp->data = data;
temp->next = NULL;
if ( head == NULL )
{
head = temp;
}
else
{
struct Node *current = head;
while ( current->next != NULL ) current = current->next;
current->next = temp;
}
}
It would be better if you check in the function whether the node was allocated.
Function Print also is wrong. It can look like
void Print( void )
{
for ( struct Node *current = head; current != NULL; current = current->next )
{
printf( "%d ", current->data );
}
}
You are writing
while(temp1 != NULL)
Make it like this
while(temp1->next != NULL)
Here, temp1 points to null at the end of loop, and you are trying to add node after null i.e.
null->next =temp;
which must be throwing error.
struct Node *curr;
void Insert(int data){
struct Node *temp = malloc(sizeof(struct Node));
temp->data = data;
temp->next =NULL;
if(head == NULL)
curr = head = temp;
else
curr = curr->next = temp;
}
void Print(){
struct Node *temp =head;
while(temp != NULL){
printf("%d ", temp->data);
temp=temp->next;
}
}