Set the number of linked list nodes C - linked-list

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;
}

Related

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

// 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;
}

Size of circular list in C++ using Double Pointer

The function in resulting in an infinite loop. It is not able to return the number of nodes. Where am I going wrong?
int Count(struct node **head)
{
printf("entered");
struct node **temp;
int count = 0;
temp = &((*head)->next);
while ((&(*temp)->next) != head)
{
printf("entered");
temp = &((*temp)->next);
count++;
}
return count;
}
In the provide source code, the while-condition is referring to addresses of pointers (where the pointer is stored) and the struct node **head is pointing to a static location in the main() but (&(*temp)->next) is pointing to the allocated of the last item.
To compare items in a linked-list, you should compare pointers struct
node * instead of addresses of pointers struct node **.
In the Count() function, because the *head exists (not compared to
NULL), the counter count should start from 1 and to count all items in the circular-list, you should start by temp = &(*head); instead of the next item temp = &((*head)->next);.
Here after is a "Minimal, Complete, and Verifiable example".
#include <stdio.h>
#include <stdlib.h>
#define NODE_MAX (5)
struct node {
struct node *next;
};
int Count(struct node **head)
{
printf("entered");
struct node **temp;
int count = 1; // at least the '*head' node exists
temp = &(*head);// &((*head)->next);
while (((*temp)->next) != *head) // use '*head'
{
printf("entered");
temp = &((*temp)->next);
count++;
}
return count;
}
int main()
{
struct node array[NODE_MAX];
struct node *head, *temp;
head = &(array[0]);
temp = head;
for(int i=1;i<NODE_MAX;i++) {
temp->next = &(array[i]);
temp = temp->next;
}
temp->next = &(array[0]);
printf("\nCount = %d\n",Count(&head));
system("pause");
return (0);
}
It would be more simple to manage linked-list at pointers level like the following example:
int Count2(struct node **head)
{
printf("entered");
struct node *temp;
int count = 1;
temp = (*head); // pointers to the first
while (temp->next != *head) // direct pointer comparison
{
printf("entered");
temp = temp->next; // natural linked-list exploration
count++;
}
return count;
}

Adding a node to linked list

I have written my first datastructures code in C and I am baffled as to what I am doing wrong. I am just trying to add a node to the front of the linked list or to an empty linked list and print the list at the end and it is resulting in segmentation fault.
#include<stdio.h>
#include<stddef.h>
#include<cstdlib>
/* Node representing each node of the linked list */
struct Node {
int data;
struct Node *next;
};
/* Fist node is always null as there are no nodes in the linked list to begin with */
struct Node *first = NULL;
void add_node(int data) {
struct Node *newptr = (Node *)malloc(sizeof(Node));
// Check if the list is empty
if (first == NULL){
printf("The list is empty\n");
newptr->data = data;
newptr->next = NULL;
first = newptr;
}
else {
printf("Adding to the existing list\n");
printf("Data in the first node is %d",first->data);
}
}
void display() {
struct Node *ptr;
printf("In the display function\n");
ptr = first;
do {
printf("Printing the data in the node %d",ptr->data);
ptr= ptr->next;
}while(ptr->next != NULL);
}
int main() {
/*
* Just try and add one node
*/
int y = 100;
printf("Adding a node \n");
add_node(y);
display();
return 1;
}
I messed up the display function, I changed it a bit to have the correct output.
The following is the new display function:
void display(struct Node *first) {
struct Node *ptr;
printf("In the display function\n");
ptr = first;
do {
printf("Printing the data in the node %d",ptr->data);
ptr= ptr->next;
}while(ptr != NULL);
}

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.

pthread_getspecific and mutex lock

I want to make thread-local buffer for strerror_r call and write my own thread-safe char * my_strerror(int) that will use thread local buffer and call strerror_r.
While reading example regarding pthread_getspecific() in Advanced Programming in Unix Environment by R.Stevens i feel discrepancy - why mutex is used in example below?
Example from book:
#include <limits.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void
thread_init(void)
{
pthread_key_create(&key, free);
}
char *
getenv(const char *name)
{
int i, len;
char *envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
if (envbuf == NULL) {
envbuf = malloc(ARG_MAX);
if (envbuf == NULL) {
pthread_mutex_unlock(&env_mutex);
return(NULL);
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for (i = 0; environ[i] != NULL; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == '=')) {
strcpy(envbuf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mutex);
return(envbuf);
}
}
pthread_mutex_unlock(&env_mutex);
return(NULL);
}
The mutex is needed for the protection of the environ variable, for example, from putenv. The lock call is badly placed, though, it's better to be immediately after the strlen.

Resources