linked list inside a linked list segmentation error - c

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
struct smallnode{
char name[4];
struct smallnode *next;
};
struct bignode {
int no;
struct smallnode *element;
struct smallnode *ehead;
struct bignode *next;
};
struct bignode *classes;
struct bignode *head;
void add_class(int no){
struct bignode *newclass = malloc(sizeof(struct bignode));
newclass->no=no;
newclass->element=NULL;newclass->ehead=NULL;
if(head==NULL){classes = newclass;head = classes;head->next=NULL;}
else{
head->next=newclass;
head = head->next;
head->next=NULL;
}
}
void add_student(int noc,char* name){
struct bignode *pointer;
pointer = classes;
int i;
// get the desired class
for(i=2;i<=noc;i++){
pointer=pointer->next;
}
//add student to class
struct smallnode *newstud;
newstud = malloc(sizeof(struct smallnode));
strcpy(newstud->name,name);
if(pointer->element==NULL){
pointer->element=newstud;
pointer->ehead = pointer->element;
pointer->ehead->next=NULL;
}
else{
pointer->ehead->next=newstud;
pointer->ehead = pointer->ehead->next;
pointer->ehead->next=NULL;
}
}
void resetdata(){
struct bignode *classpointer;
struct bignode *t;
struct smallnode *studentpointer;
struct smallnode *c;
classpointer = classes;
while(classpointer!=NULL){
t=classpointer;
studentpointer=classpointer->element;
while(studentpointer!=NULL){
c = studentpointer;
studentpointer= studentpointer->next;
free(c);
}
classpointer=classpointer->next;
free(t);
}
classes = NULL;
head = NULL;
}
int main()
{
FILE *fp,*op;
int sclasw=0;int adstud=0; int noc=1;int cp=0; char c; char sname[4]=""; int sc=0;
int cases;
classes = NULL;
head = NULL;
fp = stdin;
op = stdout;
if (fp == NULL){
printf("null");
}
cases =fgetc(fp)-'0';
fgetc(fp);
//reading
int i;
for(i=1;i<=cases;i++){
c = fgetc(fp);
while(c!='\n'){
c = fgetc(fp);
if(c==':'){sclasw=1;}
else if (c=='('&&sclasw==0){adstud=1;}
else if (c=='('&&sclasw==1){}
else if (c==')'&&sclasw==1){sclasw=0;add_class(noc);}
else if (c==')'&&adstud==1){adstud=0;add_student(cp,sname);sc=0;}
else if (sclasw==1&&c==','){
add_class(noc);
noc++;
}
else if (c==','&&adstud==1){
add_student(cp,sname);
sc=0;
}
else if (c==','&&sclasw==0&&adstud==0){
cp++;sc=0;
}
else if(adstud==1){
sname[sc]=c;
sc++;
}else if(sclasw==1){/*printf("-");*/}
}
//end reading
//coloring algo
struct bignode *classpointer;
struct bignode *classpointer2;
struct smallnode *studentpointer;
struct smallnode *studentpointer2;
int *color, totalcolor;
color=malloc((noc+1)*sizeof(int));
color[1]=1; totalcolor = 1;
int col,oldcol;
//breaker
int b1=0,b2=0,b3=0;
classpointer = classes->next;
while(classpointer!=NULL){
for(col=1;col<=totalcolor;){
color[classpointer->no]=col;
oldcol=col;
studentpointer = classpointer->element;
while (studentpointer!=NULL){//for the nth element
classpointer2 = classes;
while(classpointer2!=classpointer){//check the class
if (color[classpointer2->no]==col){
studentpointer2 = classpointer2->element;
while (studentpointer2!=NULL){// for an element
if(strcmp(studentpointer->name,studentpointer2->name)==0){//that has the same student as the nth element
col++;//if theres the same student next color
color[classpointer->no]=col;
if(col>totalcolor){//if there is no next color create one
totalcolor++;b1=1;
}
b2=1;
b3=1;
break;
}
studentpointer2 = studentpointer2->next;
}
}
classpointer2=classpointer2->next;
if(b3==1){b3=0;break;}
}
studentpointer = studentpointer->next;
if(b2==1){b2=0;break;}
}
if (color[classpointer->no]==oldcol){break;}
if(b1==1){b1=0;break;}
}
classpointer=classpointer->next;
}
//end algo
fprintf(op,"Case %i: (",i);
classpointer=classes;
while(classpointer!=NULL){
fprintf(op,"C%02i:%i",classpointer->no,color[classpointer->no]);
classpointer=classpointer->next;
if(classpointer!=NULL)fprintf(op,", ");
}
fprintf(op,")\n");
resetdata();
sclasw = 0; adstud = 0; noc=1;cp=0;sc = 0;
}
return 0;
fclose(fp);
fclose(op);
}
//EDIT
Input:
1
Case 1: (C01,C02,C03,C04,C05,C06,C07,C08,C09,C10,C11),(RDA,ALB,NAC,EDF,BMG,VLJ,IVL,LGM,EGN,KSO,EST,VIV),(MCA,EDF,SLF,ADG,BCG,AAI,RRK,LGM,RLM,JGP,LRQ,WAR,KLS,DDY),(ABC,BBD,GCF,ADG,AKL,BCL,MIN,JGP,RSQ,DBU,IEY,RAW,ESZ),(ANA,JCA,CAB,NAC,GCF,GLH,VLJ,LLM,MAN,PEP,PQQ,ERR,SET,MAV,REW),(BBC,EDD,HSE,EST,ELG,ISH,JEI,EMJ,RRK,TPL,RER,EPS,AVU,CDW,ELY),(ALA,MCA,ABB,BCF,GLH,AKL,HGN,RON,JGP,ALQ,EPR,ABT,KEV,YEZ),(CDC,ISH,ABI,DHJ,ESM,FBM,RMN,PEP,VIR,JLS,LOT,MAV,TEX),(AAA,HLA,BBD,WRE,ECG,HLH,DHJ,RON,TSO,PQQ,MBT,REW,BAX,TRY,BDZ),(MCA,JCA,BCF,EGG,AAI,XTK,WIL,CSM,HLO,RSP,APR,RER,JET,DBU),(RDA,BBB,CLC,ECG,MNH,EMJ,JOK,ARM,NFM,EGN,RCN,RSP,LEQ,YIR,AVU),(ADB,WDB,BKC,CLC,SDE,UKF,BMG,HRH,BTK,LGM,QJP,EPS,KLS,BST,YNZ)
Output(in codeblocks which works just fine):
Case 1: (C01:1, C02:2, C03:1, C04:2, C05:3, C06:3, C07:1, C08:4, C09:4, C10:2, C11:4)
PS. I've already edited my source code such that there are no minor mistakes like insufficient memory for array.
This program does graph coloring by using 2 arrays. One for the classes and the other or student. The bigger linked list, which is the one for classes, has an element of a smaller linked list in each node;
Hackerrank's compiler says that it has a segmentation error, but it works fine when I run it in code blocks.
I've been stuck with this for days and I dont have any clue why this is happening. Please help me :(

Related

I keep getting Segmentation Fault when i try to add a new WaitingRoom in my list

So basically what my code does is creates a WaitingRoom as the HEAD of a list and then it adds students in it ordered alphabetically, this works just fine, but when i try to add another watiningroom it gives me seg fault at the insertinRoom function at firts if.
This is my code, but when i run it with only one WaitingRoom created it works perfectly but if i add another one then it gives me segfault.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct studenti{
char name[100];
struct studenti* next;
}studenti;
typedef struct WaitingRoom{
int ID;
char parola[100];
struct WaitingRoom* next;
struct studenti* next_S;
}WaitingRoom;
studenti* CreateStudent(char* name)
{
studenti* S = (studenti*)malloc(sizeof(studenti));
strcpy(S->name,name);
S->next = NULL;
return S;
}
WaitingRoom* createWaitingRoom(int ID, char* parola){
WaitingRoom* WR = (WaitingRoom*)malloc(sizeof(WaitingRoom));
strcpy(WR->parola,parola);
WR->ID = ID;
WR->next = NULL;
return WR;
}
void insertinRoom(WaitingRoom* WR,char* name){
studenti* S;
S = CreateStudent(name);
if(WR->next_S == NULL || strcmp(WR->next_S->name,name)>0){
S->next=WR->next_S;
WR->next_S = S;
}
else{
studenti* current = WR->next_S;
while(current->next !=NULL && strcmp(current->next->name,name)>0)
{
current=current->next;
}
S->next = current->next;
current->next = S;
}
}
void printWaitingRoom(WaitingRoom* WR){
studenti* current = WR->next_S;
printf("Waiting Romom este %d cu parola %s\n",WR->ID,WR->parola);
while(current!=NULL){
printf("%s\n",current->name);
current = current->next;
}
}
void printall(WaitingRoom* WR){
WaitingRoom* current = WR;
while(current!=NULL){
printWaitingRoom(current);
current = current->next;
}
}
int main()
{
WaitingRoom* WR1 = createWaitingRoom(6969,"Muiedinamo");
insertinRoom(WR1,"BOOm1");
insertinRoom(WR1,"AOOm2");
insertinRoom(WR1,"DOOm3");
insertinRoom(WR1,"COOm4");
/*
WaitingRoom* WR2 = createWaitingRoom(1234,"AStae ");
insertinRoom(WR2,"B1");
insertinRoom(WR2,"AO2");
insertinRoom(WR2,"D3");
insertinRoom(WR2,"C4");
WR1->next = WR2;
*/
printWaitingRoom(WR1);
//printall(WR1);
return 0;
}
I was expecting to created my WaitingRoom and then connecting the waitingrooms and printing them 1 by 1 and the the hole list with "PrintAll" function.

String input by linked list

Is there any way to take a string input(as like we take for any integer) by linked list??
For example:This code is showing run time error:
struct node
{
char c;
struct node *link;
};
while(1)
{
val=getch();
if(val!=10)
add(&a[i],val);
else
break;
}
and I want to take any input string like - "asdfghj", of which string length was not known?
Given that you have a LinkedList-class that acts as an interface to the linked list and that it has the function addNode() that adds a node in a correct manner to the list.
I also assume that what you want to know is how to make every char in the inputted string a node in the linked list and that you know how to manage a linked list.
And assuming you're using C++11
int main()
{
LinkedList list;
string input;
cin >> input;
for(auto i: input)
{
list.addNode(i);
}
}
example for C
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char c;
struct node *link;
} Node;
typedef struct s_ {
Node *top;
Node *curr;
} String;
Node *Node_new(char ch){
Node *p = calloc(1, sizeof *p);
p->c = ch;
return p;
}
String *String_new(void){
String *p = calloc(1, sizeof *p);
return p;
}
void String_drop(String *s){
Node *p = s->top;
while(p){
s->curr = p;
p = p->link;
free(s->curr);
}
//s->top = s->curr = NULL;
free(s);
}
void String_add(String *s, char c){
if(s->top == NULL){
s->curr = s->top = Node_new(c);
} else {
s->curr = s->curr->link = Node_new(c);
}
}
String *get_string(FILE *fp){
String *s = String_new();
int ch;
while(EOF!=(ch=fgetc(fp)) && ch !='\n'){
String_add(s, (char)ch);
}
return s;
}
void put_string(String *s){
Node *p;
for(p = s->top; p ; p = p->link)
putchar(p->c);
putchar('\n');
}
int main(void) {
String *s = get_string(stdin);
put_string(s);
String_drop(s);
return 0;
}
You can think easily. As You just can declare a string variable instead of char. And after that You can take input normally by creating a struct variable. For example:
#include <bits/stdc++.h>
using namespace std;
struct node
{
string s;
struct node *link;
};
int main(){
node ob;
cin>>ob.s;
cout<<ob.s;
}

Seg Fault in BST inorder traversal

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define n 5
struct node
{
int num;
char *symbol;
char *code;
struct node *left;
struct node *right;
}*root_ptr, *current, *previous;
void form_bst_of_dividing_positions();
void inorderTraversal(struct node *);
int dividing_positions[n], counter = 0;
int main(int argc, char *argv[])
{
//code to populate dividing_positions
//tree structure formation
counter = 0;
root_ptr = malloc(sizeof(struct node));
root_ptr->num = dividing_positions[0];
root_ptr->code = root_ptr->symbol = NULL;
root_ptr->left = root_ptr->right = NULL;
form_bst_of_dividing_positions();
inorderTraversal(root_ptr);
return 0;
}
void form_bst_of_dividing_positions()
{
for(i=1;i<n;i++)
{
if(dividing_positions[i]==-1)
break;
else
{
struct node nodeToAdd;
nodeToAdd.num = dividing_positions[i];
nodeToAdd.code = nodeToAdd.symbol = NULL;
nodeToAdd.left = nodeToAdd.right = NULL;
current = previous = root_ptr;
while(current!=NULL)
{
previous = current;
current = (dividing_positions[i]<(current->num))? current->left : current->right;
}
if(nodeToAdd.num<(previous->num))
previous->left = &nodeToAdd;
else
previous->right = &nodeToAdd;
}
}
}
void inorderTraversal(struct node *no)
{
if(no!=NULL)
{
inorderTraversal(no->left);
printf("%d ", no->num);
inorderTraversal(no->right);
}
}
Above code gives me Segmentation fault .. in Codeblocks the output window prints 4 infinitely. 2, 3, 1, 4 = to be inserted into BST. Ive converted my Java code to C, are there any specifics to be handled in my above code?
Thanks..
Your nodeToAdd is a local variable, its address becomes invalid once you leave that code block. You should use malloc to create new nodes (and free them with free eventually).
Use malloc everytime you add a new node.

i got some issues reading words from a .txt file in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORD_LENGHT 30
typedef struct numnode
{
char* dataPtr;
struct numnode* next;
} NUMNODE;
typedef struct num
{
NUMNODE* head;
} NUM;
//////
//////
//////
int main()
{
char *wp;
char word[80];
int total=0;
FILE *test= fopen("book.txt", "r");
while (fscanf (test, "%s",word) == 1)
{
//printf("%s\n",word); //counting how many words in a book.txt
total++;
}
if (total==0)
{
printf("File not found\n"); //if no word, then return
return;
}
NUM* dic;
dic=(NUM*)malloc(sizeof(NUM)*total);
NUMNODE* temp;
temp=dic->head;
FILE*file = fopen("book.txt", "r");
while(!feof(file))
{
wp=malloc(100);
printf("test1\n");
fscanf(file,"%s",wp);
strcpy(temp->dataPtr,wp); //strcpy is the error part
printf("test2\n");
temp=temp->next;
}
return;
}
this c code read word by word from book.txt and put them to linked
list. i got some issues with !feof(file) part.Couldnt figure out what
to do.i think strcpy in this loop is the reason of this issue.im
waiting for your helps :3
Error is because the struct member dataPtr is a pointer, not an array. So the strcpy call
strcpy(temp->dataPtr,wp);
is wrong because it accesses illegal memory invoking undefined behaviour. What you need is
typedef struct numnode
{
char dataPtr[100]; // dataPtr changed to an array type
struct numnode* next;
} NUMNODE;
Please note that dataPtr must be at least the size of the buffer pointed to by wp.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORD_LENGHT 30
typedef struct numnode {
char* dataPtr;
struct numnode* next;
} NUMNODE;
typedef struct num {
NUMNODE* head;
} NUM;
int main(){
NUM dic = { NULL };
char word[WORD_LENGHT];
int total=0;//num of word
FILE *file= fopen("book.txt", "r");
NUMNODE *curr = NULL, *temp;
while (fscanf(file, "%29s", word) == 1) {
temp = malloc(sizeof(*temp));
temp->dataPtr = malloc(strlen(word) + 1);
temp->next = NULL;,
strcpy(temp->dataPtr, word);
if(curr){
curr = curr->next = temp;
} else {
dic.head = curr = temp;
}
++total;
}
if (total==0){
printf("File does not has word\n");
return;
}
//test print
printf("%d\n", total);
if(total>1){
printf("%s\n", dic.head->dataPtr);
printf("%s\n", dic.head->next->dataPtr);
}
//do something
return;
}
,

storing an array as a linked list in C

I'm working in C and am having some trouble. I need to store an array of chars (string) across a linked list. In other words, convert a string to a linked list. Basically, one character per node. For example string, dog\0, rather then storing a null character in the last node it would just point to a null pointer to signify the end of the string…… d->o->g->NULL
An suggestions would be great, thank you
int main(){
char *string;
string = malloc(sizeof(char)*100);
strcpy(string,"cheese");
node *list = NULL;
list = createNode(string[0]);
int i;
for(i=1;i<strlen(string);i++){
// this is where I'm stuck, the first char 'c'is in,
// I'm guessing i wanna loop through and
// store each char in a new node ?
}
return 0;
}
node *createNode(char data){
node *ptr = malloc(sizeof(node));
if (ptr == NULL)
{
return NULL;
}
ptr->data = data;
ptr->next = NULL;
return ptr;
}
Here is how to do this in C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
node *next;
char data;
};
node *createNode(char data, node *parent) {
node *ptr=(node*)malloc(sizeof(node));
if(ptr==NULL) {
fprintf(stderr, "Memory allocation error.\n");
exit(1);
}
if(parent!=NULL) parent->next=ptr;
ptr->data=data;
ptr->next=NULL;
return ptr;
}
int main() {
char str[]="cheese";
// Store the string to the list
node *first=NULL, *cur=NULL;
for(int i=0, len=strlen(str); i<len; i++) {
cur=createNode(str[i],cur);
if(first==NULL) first=cur;
}
// Now print it out
cur=first;
while(cur!=NULL) {
printf("%c\n", cur->data);
cur=cur->next;
}
_getwch();
return 0;
}
If C++ is OK then here is a working sample:
#include <iostream>
#include <list>
using namespace std;
int main() {
char str[]="cheese", chr;
// Store the string in the list
std::list<char> clist;
for (int i=0, len=strlen(str); i<len; i++)
clist.push_back(str[i]);
clist.push_back('\0');
// Display the list
do {
chr=clist.front();
cout<<chr<<endl;
clist.pop_front();
} while(chr);
_getwch();
return 0;
}

Resources