Segmentation Fault issue, unable to detect [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Can someone help me with this piece of code. I am getting segmentation fault. Kindly help me out as to where I am going wrong.
#include <stdio.h>
#include <stdlib.h>
struct city
{
int x;
int pop;
struct city *next;
};
struct list
{
struct city *head;
};
void insert(struct list *list1,int a,int b)
{
struct city *node = (struct city *)malloc(sizeof(struct city));
node->x=a;
node->pop = b;
if(list1->head!=NULL)
{
node->next=list1->head;
}
list1->head=node;
}
void initialize_list(struct list *list1)
{
list1->head = NULL;
}
void display(struct list *list)
{
struct city *temp = list->head;
while(temp!=NULL)
{
printf("%d %d\n",temp->x,temp->pop);
temp=temp->next;
}
free(temp);
}
void getdata(int *x)
{
char s[1000];
char c;
scanf("%[^\n]%*s",s);
char *p=s;
int i =0;
while(*p!='\0')
{
while(*p==' ' && *p!='\0')
p++;
if(*p!='\0')
x[i] = atoi(p);
while(*p!=' ' && *p!='\0')
p++;
i++;
}
}
int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
int total(struct list *link)
{
struct city *r1,*r2;
r1=link->head;
r2 = r1;
int S=0;
while(r1!=NULL)
{
r2 = r1;
while(r2!=NULL)
{
S=S+max(r1->pop,r2->pop)*abs((r2->x)-(r1->x));
r2=r2->next;
}
r1=r1->next;
}
printf("\n%d",S);
free(r1);
free(r2);
return S;
}
int main()
{
int T;
int *x,*pop;
int _no_city;
char c;
scanf("%d",&T);
struct list **link = (struct list **)malloc(T*sizeof(struct list*));
for(int i=0;i<T;i++)
{
link[i]=(struct list *)malloc(sizeof(struct list));
}
for(int i =0;i<T;i++)
{
scanf("%d",&_no_city);
x = (int *)malloc(_no_city*sizeof(int));
pop = (int *)malloc(_no_city*sizeof(int));
while((c= getchar()) != '\n' && c != EOF)
fflush(stdin);
getdata(x);
getdata(pop);
initialize_list(link[i]);
for(int j=0;i<_no_city;j++)
{
insert(link[i],x[j],pop[j]);
}
free(x);
free(pop);
}
for(int i=0;i<T;i++)
{
printf("%d",total(link[i]));
}
}
Is the problem lying with my declaring a pointer to pointer, I did that so that I can create an array of pointers of variable length.

There are quite a few bugs in your program, but this one
for(int j=0;i<_no_city;j++)
{
insert(link[i],x[j],pop[j]);
}
will run off the end of x and pop because your loop condition is wrong, and is probably the cause of your crash.

Related

Segmentation fault while implementing stack as an array

This is a menu-driven program that carries out basic stack operations using arrays in the C programming language. The functions that are performed are push, pop, peep,isempty and isfull.
#include<stdio.h>
#include<stdlib.h>
struct stack
{
long int top;
long int size;
char* key;
};
int is_empty(struct stack *s) //check if its empty
{
if(s->top==-1)
{
return -1;
}
else
{
return 1;
}
}
int is_full(struct stack *s) //check if its full
{
if (s->top ==s->size-1)
{
return -1;
}
else
{
return 1;
}
}
void push(struct stack *s, char x) //pushes into stack
{
int check;
check = is_full(s);
if(check==-1)
{
printf("-1\n");
}
else
{
s->top = s->top+1;
s->key[s->top]=x;
}
}
void pop(struct stack *s) //deletes the last element
{
int check;
check = is_empty(s);
if(check==-1)
{
printf("-1\n");
}
else
{
char k;
k = s->key[s->top];
printf("%c\n",k);
s->top--;
}
}
void peep(struct stack *s) //prints the last element without deleting
{ int check;
char k;
check = is_empty(s);
if (check == -1)
{
printf("-1\n");
}
else
{
k = s->key[s->top];
printf("%c \n",k);
}
}
int main()
{
char ch;
char x;
long int n;
struct stack *s;
scanf("%ld ", &n);
s->size = n; //initialise the size
s->top = -1; //setting as -1 base case
s->key= (char *)malloc(n*sizeof(char)); //dynamic allocation of keys
while(1)
{
scanf("%c ",&ch);
switch(ch)
{
case 'i':
scanf("%c ",&x);
push(s,x);
break;
case 'd':pop(s);
break;
case 'p':peep(s);
break;
case 't':exit(0); //termination case
}
}
return 0;
}
This is a C program that is working for me in some online compilers but in VScode and other compilers, it's showing a segmentation fault without any output. This is an implementation of stack using arrays. Is it a problem with any of the scanf functions?
You have created a pointer variable s and then access the size field on that struct.
struct stack *s;
scanf("%ld ", &n);
s->size = n; //initialise the size
Except s doesn't actually point to anything at this point. You need to either statically or dynamically allocate memory for that struct.
struct stack s;
Or:
struct stack *s = malloc(sizeof(struct stack));

Previous question about how a linked list and a stack works [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Yesterday I saw this question from a new contributor about how a linked list works in C. Since my answer might help someone I decided to re-post the question and provide my code.
First I modified the OP code as Antti Haapala and Weather Vane suggested. Below is my version:
#include <stdio.h>
#include <stdlib.h>
typedef struct suppliers {
int idSUP;
int coonection;
int bill;
suppliers* next;
}suppliers;
void printlist(suppliers* h);
void insert(suppliers* head, int idSUP, int coonection, int bill);
void main() {
int idSUP;
int coonection;
int bill;
suppliers* head = NULL;
printf("please enter supplier data\n");
while (scanf("%d,%d,%d", &idSUP, &coonection, &bill) != EOF)
insert(head, idSUP, coonection, bill);
printlist(head);
}
void insert(suppliers* head, int idSUP, int coonection, int bill) {
suppliers* t, temp;
t = (struct suppliers*)malloc(sizeof(struct suppliers));
if (t == NULL) {
printf("ERROR");
}
t->idSUP = idSUP;
t->bill = bill;
t->coonection = coonection;
t->next = head;
head = t;
}
void printlist(suppliers* h) { while (h != NULL) { printf("%d", h->bill); h = h->next; } }
I entered the following but the program hung on the scanf after I entered Ctrl+Z.
please enter supplier data
1,1,1
^Z
I don't use scanf much, so I don't know what the problem is. Perhaps this is the same problem the OP had. I don't know. Does anyone know why the code from the OP of the previous question I linked to above doesn't produce any output?
Below is my suggested revisions.
I took a different approach on how the input was entered and how the head structure was implemented. Instead of using a pointer to supplies I created a q structure that held pointers to the first node and the last node. The last node pointer was used to quickly update its next pointer with the node that was just created with the malloc.
Having the last pointer, it wasn't that hard to implement a stack. (Okay, it was hard for me because I'm not all that swift. ;)
I also renamed the fields to have longer names, as is my wont.
Below is my revised code:
#include <stdio.h>
#include <stdlib.h>
typedef struct suppliers {
int idSupplier;
int connection;
int bill;
suppliers* nextPtr;
suppliers* previousPtr;
}suppliers;
typedef struct {
size_t qCount;
suppliers* firstPtr;
suppliers* lastPtr;
}q;
void insert(q* list, int idSupplier, int connection, int bill);
void printList(q list);
void printStack1(q stack);
void printStack2(q stack);
int main() {
int idSupplier;
int connection;
int bill;
int scanCount;
q list;
q stack;
list.firstPtr = NULL;
list.lastPtr = NULL;
list.qCount = 0;
stack.firstPtr = NULL;
stack.lastPtr = NULL;
stack.qCount = 0;
printf("Please enter supplier data. Enter 'q' to quit.\n");
scanCount = scanf("%d, %d, %d", &idSupplier, &connection, &bill);
while (scanCount) {
insert(&list, idSupplier, connection, bill);
insert(&stack, idSupplier, connection, bill);
scanCount = scanf("%d, %d, %d", &idSupplier, &connection, &bill);
}
if (list.qCount > 0) {
printList(list);
}
if (stack.qCount > 0) {
printStack1(stack);
printStack2(stack);
}
}
void insert(q* queue, int idSupplier, int connection, int bill)
{
suppliers* t;
queue->qCount++;
t = (suppliers*)malloc(sizeof(suppliers));
if (t == NULL) {
printf("ERROR");
}
if (queue->firstPtr == NULL) {
queue->firstPtr = t;
}
else {
queue->lastPtr->nextPtr = t;
}
t->previousPtr = queue->lastPtr;
queue->lastPtr = t;
t->idSupplier = idSupplier;
t->bill = bill;
t->connection = connection;
t->nextPtr = NULL;
}
void printList(q list)
{
suppliers* currentPtr;
printf("\n\n");
currentPtr = list.firstPtr;
while (currentPtr != NULL) {
printf("sup=%-3d conn=%-3d bill=%-3d\n", currentPtr->idSupplier,
currentPtr->connection, currentPtr->bill);
currentPtr = currentPtr->nextPtr;
}
}
void printStack1(q stack)
{
suppliers* currentPtr;
if (stack.lastPtr != NULL) {
printf("\n\n");
currentPtr = stack.lastPtr;
do {
printf("sup=%-3d conn=%-3d bill=%-3d\n", currentPtr->idSupplier,
currentPtr->connection, currentPtr->bill);
currentPtr = currentPtr->previousPtr;
}
while (currentPtr != stack.firstPtr);
printf("sup=%-3d conn=%-3d bill=%-3d\n", currentPtr->idSupplier,
currentPtr->connection, currentPtr->bill);
}
}
void printStack2(q stack)
{
suppliers* currentPtr;
printf("\n\n");
currentPtr = stack.lastPtr;
for (size_t i = stack.qCount; i > 0; i--) {
printf("sup=%-3d conn=%-3d bill=%-3d\n", currentPtr->idSupplier,
currentPtr->connection, currentPtr->bill);
currentPtr = currentPtr->previousPtr;
}
}
Here is my output:
Please enter supplier data. Enter 'q' to quit.
1, 2, 3
4, 5, 6
10, 11, 12
20, 21, 22
q
sup=1 conn=2 bill=3
sup=4 conn=5 bill=6
sup=10 conn=11 bill=12
sup=20 conn=21 bill=22
sup=20 conn=21 bill=22
sup=10 conn=11 bill=12
sup=4 conn=5 bill=6
sup=1 conn=2 bill=3
sup=20 conn=21 bill=22
sup=10 conn=11 bill=12
sup=4 conn=5 bill=6
sup=1 conn=2 bill=3
Storing the count of the number of nodes created allowed me to have two different ways of printing the stack. Personally I prefer printStack2, but that's just me.
Hope this helps.
Update: I'm going to mark this as the correct answer, even though it's not. This is one way to implement this stuff, but not likely to be the best way to do it.

Finding path between nodes using BFS in C language

I'm new to C language and it's been harder for me to work with pointers after working in Java😥
I was trying to write a code of finding a path (not necessary minimum) between two nodes in a graph using breadth-first-search.
Here is my code :
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 200
void push(int a);
int pop(void);
void bfs(int a,int b,int len);
int nextnode(int a);
typedef struct node{
int data;
struct node* next;
}node;
int res[MAXSIZE];
int visited[MAXSIZE];
int rear,front;
node* graph[MAXSIZE];
int len;
int path[MAXSIZE];
int nextnode(int a)
{
if(graph[a]==NULL)
return -1;
else
{
struct node* c=graph[a];
while(visited[c->data]!=1 && c!=NULL)
{
c=c->next;
}
if(c==NULL)
return -1;
else
return c->data;
}
}
void push(int a)
{
path[rear]=a;
rear++;
}
int pop()
{
if(front==rear)
return -1;
int num=path[front];
front++;
return num;
}
int main()
{
rear=0;
len=0;
front=0;
int n,e;
int i,a,b;
printf("%s\n%s", "Inputting Graph... ","Enter number of nodes and edges: ");
scanf("%d %d",&n,&e);
printf("%s %d %s\n", "Graph Created with",n,"nodes without any edge.");
printf("%s\n","Enter the edges in 1 2 format if an edge exist from Node 1 to Node 2" );
for(i=1;i<=n;i++)
{
graph[i]=NULL;
visited[i]=0;
}
struct node* new = (struct node*)malloc(sizeof(struct node));
for(i=0;i<e;i++)
{
scanf("%d %d",&a,&b);
new->data=b;
new->next=NULL;
struct node* curr=graph[a];
if(curr==NULL)
{
graph[a]=new;
}
else
{
while(curr->next!=NULL)
{
curr=curr->next;
}
curr->next=new;
}
}
printf("%s\n", "Graph Created Successfully.");
printf("%s", "Enter the node numbers between which the path is to be found between: ");
scanf("%d %d",&a,&b);
bfs(a,b,0);
printf("Length is %d\n",len);
for(i=1;i<=len;i++)
{
printf("%d\n",res[len]);
}
}
void bfs(int a,int b,int len)
{
int c;
visited[a]=1;
int flag=0;
while(a!=-1)
{
c=nextnode(a);
while(c!=-1)
{
c=nextnode(a);
if(c==b)
{
flag=1;
break;
}
push(c);
visited[c]=1;
}
len++;
res[len]=a;
if(flag==1)
{
res[len]=b;
break;
}
a=pop();
}
}
I know it's huge, but please mind going through it once. The problem I'm getting is Segmentation Fault after I input all the values, and before dfs() function call! Please Help.
For understanding: I have used array of Lists. Each array index denotes a node and the list denotes all the edges it is connected to. eg: if my Graph has 1->2, 1->3, 2-3 edges;
graph[1] will have a list 2->3->NULL. And graph[2] will have 3->NULL.
Thank you.
EDIT
As pointed out by Aditi, the error was in the line where nextnode function ran the while loop. After changing the code to
while(c != NULL && visited[c->data] == 1 )
the program ran flawlessly.
Thanks!
I think what you are trying to do is not graph[i] = NULL but graph[i]->next = NULL

Simple C trie program goes wrong (segmentation fault) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
In order to understand tries I am creating this very simple C program that takes from user 10 nums from 0 to 9 as children of the trie. The final step is to print this nums with the function print, but I am getting a segmentation fault:
#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
int data;
struct list *ar[10];
} list;
void insert(list *head);
void print(list *head);
int main(void)
{
printf("hello\n");
list *root = malloc(sizeof(list));
insert(root);
print(root);
}
void insert(list *head)
{
int a, i;
if (head == NULL) {
return;
}
for (i = 0; i < 10; i++) {
printf("Give Num 0-9\n");
scanf("%i", &a);
head->ar[a] = malloc(sizeof(head));
head = head->ar[a];
head->data = a;
}
}
void print(list *head)
{
if (head == NULL) {
return;
}
while (head != NULL) {
for (int i = 1; i < 10; i++) {
if (head->ar[i] != NULL) {
printf("%i", i);
head = head->ar[i];
break;
}
}
}
printf("\n");
}
There are several issues with your code:
The first mention of malloc doesn't actually initialize the memory (the ar field). You should initialize it properly
list *root = malloc(sizeof(list));
Is missing initialization, e.g.
root->data = 0;
for (size_t ii = 0; ii < 10; ii++) {
root->ar[ii] = NULL;
}
When you are actually gathering input, you allocate only enough memory for the pointer, not for the actual list itself.
head->ar[a] = malloc(sizeof(head));
should be initialized as above (head = malloc(sizeof(list)); for (size_t ...
There seems to be an infinite loop when actually running your program (after correcting all these issues).
EDIT: Remove calloc...

Dynamic stack in C [pop crash] [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Im making a program to convert a decimal int to binary using a dynamic stack.
It crashes on the last pop.
ex. num: 4 output: 10crash
#include <stdio.h>
struct stack {
struct stack *prev;
int val;
struct stack *next;
};
struct stack *first,*cur,*tmp;
struct stack *GETNODE(){
struct stack *pt = (struct stack *)malloc(sizeof(struct stack));
};
int counter=1;
void push(int val){
tmp=GETNODE();
tmp->prev=NULL;
tmp->val=val;
tmp->next=NULL;
if(first==NULL){
first=tmp;
cur=first;
}else{
tmp->prev=cur;
cur->next=tmp;
cur=tmp;
}
counter++;
};
int pop(){
int val=tmp->val;
cur=tmp->prev;
free(tmp);
tmp=cur;
tmp->next=NULL;
counter--;
return(val);
};
main(){
int num = 4;
while(num!=0){
push(num%2);
num/=2;
}
while(counter!=1){
printf("%d ",pop());
}
}
The problem is in your pop function. If you think about how it operates, in the final pass you will free(tmp), which is currently pointing to the very first item. After you free it, you then assign:
tmp->next=NULL;
You are trying to dereference an invalid pointer at this point.
I made a lot of changes to your code. Mainly, it was far too complicated - only a singly linked list was needed, and you don't need a counter - just track the list pointer. Your GETNODE() function did not return a value, causing undefined behaviour in the calling function. I simplified that too, there is no need for a separate function to allocate memory because malloc() already does that.
#include <stdio.h>
#include <stdlib.h>
struct stack {
struct stack *prev;
int val;
};
struct stack *first = NULL;
void push(int val){
struct stack *pt = malloc(sizeof(struct stack));
if (pt == NULL){
printf ("Bad call to malloc()\n");
exit (1);
}
pt->prev=first;
pt->val=val;
first = pt;
}
int pop(){
int val;
struct stack *pt = first;
if (first == NULL)
return -1;
val=first->val;
first = first->prev;
free(pt);
return(val);
}
void dec2bin(int num){
printf("%-5d", num);
while(num!=0){
push(num%2);
num/=2;
}
while(first){
printf("%d",pop());
}
printf("\n");
}
int main(void){
dec2bin (4);
dec2bin (129);
dec2bin (160);
return 0;
}
Program output:
4 100
129 10000001
160 10100000
I change some part of your code and your code working now.
#include <stdio.h>
#include <stdlib.h>
struct stack {
struct stack *prev;
int val;
struct stack *next;
};
struct stack *first, *cur, *tmp;
int counter = 0;
struct stack *GETNODE()
{
return malloc(sizeof(struct stack));
}
void push(int val)
{
tmp = GETNODE();
tmp->prev = NULL;
tmp->val = val;
tmp->next = NULL;
if (first == NULL) {
first = tmp;
cur = first;
} else {
tmp->prev = cur;
cur->next = tmp;
cur = tmp;
}
counter++;
}
int pop(void)
{
int val = cur->val;
tmp = cur;
cur = cur->prev;
free(tmp);
counter--;
return val;
}
int main(int argc, char *argv[])
{
int num;
scanf("%d", &num);
while (num != 0) {
push(num % 2);
num /= 2;
}
while (counter != 0)
printf("%d ", pop());
printf("\n");
}

Resources