segmentation error in ubuntu - c

Please tell me why the segmentation error is there in my program there is no error .
I also tried to debug it but it never goes inside the for statement.
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node* link;
} *start;
main()
{
int i,n,m;
start=NULL;
printf("enter the number of nodes you want");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the element you want to insert");
scanf("%d",&m);
create_list(m);
}
}
create_list(int data)
{
struct node *q,*temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=data;
temp->link=NULL;
if(start==NULL)
start=temp;
else
{
while(q->link!=NULL) q=q->link;
q->link=temp;
}
}

You forgot to initialize q before using it:
q = start;
while(q->link!=NULL)

1.You haven't initialized q in create_list() and used it -
while(q->link!=NULL)
Intialize q=start; before this loop.
2.Also free the allocated memory for temp in function.
3.main() should be int main(void) and what is type of create_list? Declare its prototype before main.

In the function create_list local pointer q was not initialized
struct node *q,*temp;
^^^
However it is accessed in the loop
while(q->link!=NULL)
I think you mean the following
else
{
q = start;
while ( q->link != NULL ) q = q->link;
q->link = temp;
}
Take into account that the function should be declared before its usage. Place it declaration for example before main. And its return type shall be void and specified explicitly. Also function main shall have return type int.
For example
void create_list( int data );
int main( void )
{
//...
And it is a good idea to free all dynamically allocated memory before exiting the program.
Also header <malloc.h> is not a standard C header. You should use <stdlib.h> instead.

After all suggestions from the above it will be clearly in the future if you try to show some work of your clear codding and to respect the minimum standard.
Here is a way of how should be looking your code:
#include<stdio.h>
#include<stdlib.h> /* You need stdlib not malloc */
void create_list(int data); /* If you don't declare your function the compiler doesn't know nothing about create_list */
struct node{
int data;
struct node* link;
}*start;
int main(void){ /* Here return type of main is int and if no arg needed should be used void */
int i,n,m;
start=NULL;
printf("enter the number of nodes you want");
if((scanf("%d",&n)) != EOF) /* always check scanf's return */
for(i=0;i<n;i++){
printf("enter the element you want to insert");
if((scanf("%d",&m)) != EOF) /* here the same: always check scanf's return */
create_list(m);
}
return 0; /* return of main should be 0 or one of the following: EXIT_SUCCESS or EXIT_FAILURE, but 0 will be ok because it is standard*/
}
void create_list(int data){ /* here should be explicit what kind of function is */
struct node *q,*temp;
temp=(struct node *)malloc(sizeof(struct node)); /* if you allocate memory dynamically ..... */
temp->data=data;
temp->link=NULL;
if(start==NULL){
start=temp;
}else{
q = start;
while(q->link!=NULL){
q=q->link;
q->link=temp;
}
}
free(temp); /* .....then always free it */
}

Related

Linked list always show empty

REQUIREMENT / QUESTION 2
In computing, the process identifier (normally referred to as the process ID or PID), is a number used by most operating system kernels, to uniquely identify an active process. The PIDs are usually allocated on a sequential basis, beginning with 0 and rising to a maximum value that varies from system to system. Create a link list to store the PIDs. To create a new PID, createPID() function is used.
Each PID is inserted into the list at the beginning of the list, using insertPID() function. Once a process is completed, that particular PID is deleted, using the deletePID() function.
The assessment will be done based on the following criteria:
A proper writing of C codes and its structure
The ability of program to be compiled and executed
Implementation of correct programming techniques
Complete documentation and correct submission
Note: You must write C programming codes for this assignment.
I already create a code:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *link;
};
void createPID ();
void insertPID (struct node *start,int x);
struct node * deletePID (struct node * start,int x);
void displayPID(struct node *start);
struct node * start;
int main()
{
createPID();
insertPID(start,0);
insertPID(start,1);
insertPID(start,2);
displayPID(start);
start=deletePID(start, 3);
displayPID(start);
}
void createPID(){
struct node *start = NULL;
}
void displayPID(struct node *start)
{
struct node *p;
if(start == NULL)
{
printf("List is empty\n");
return;
}
printf("List is :");
p=start;
while(p!=NULL)
{
printf("%d\t",p->info);
p=p->link;
}
printf("\n");
}
/*End of displayList()*/
void insertPID(struct node * start, int data)
{
struct node *temp,*p;
p=start;
while (p!=NULL)
{
if(p->link==NULL)
break;
p=p->link;
}
temp=(struct node *)malloc (sizeof (struct node));
temp->info=data;
if(p==NULL)
start=temp;
else
{
temp->link= p->link;
p->link= temp;
}
}
struct node* deletePID(struct node * start,int x){
struct node *temp, *p;
if(start == NULL)
{
printf("List is empty\n");
return start;
}
/*Deletion of first node */
if(start->info == x)
{
temp=start;
start= start->link;
free(temp);
return start;
}
/*Deletion in between or at the end */
p=start;
while (p->link != NULL)
{
if (p-> link -> info== x)
break;
p=p-> link;
}
if(p->link==NULL)
printf("Element %d not in list \n\n",x);
else
{
temp=p->link;
p->link=temp->link;
free (temp);
}
return start;
}
The result always empty list. Need help to figure out what is the problem ?
Problem is in insertPID function. start as argument of function is local variable, it hides global start and the line below
start = temp;
only modifies local start, global start is not affected and it is always NULL.
If you want to update start pointer you need to pass it by pointer-to-pointer:
void insertPID (struct node **start,int x);
//...
insertPID(&start,0);
insertPID(&start,1);
insertPID(&start,2);
//...
void insertPID(struct node ** start, int data)
{
//...
p=*start;
//...
if(p==NULL)
*start=temp;
//...
}
void createPID(){
struct node *start = NULL;
}
I assume this function wants to set start (global) to 0 ? So it should be:
void createPID(){
start = NULL;
}
Your version introduces local start variable, so global is not affected.
But the call of createPID is superfluous here because start as global variable is initialized to 0 before main starts executing.

Segmentation Fault (singal 11 sigsegv) with linked list

Was writing a program to practice before with linked lists and pointers before pset5 and am left with two memory errors that i have not been able to remedy.
#include <stdio.h>
#include <stdlib.h>
//define struct for Nodes
typedef struct list
{
int data;
int key;
struct list* next;
}Node;
//function declarations
Node* create(int a, int *counter);
void insert(int a, int *counter);
void delete_list();
void printlist();
//global pointers
Node* Head = NULL;
Node* Current = NULL;
int main()
{
int *keycounter =(int*)malloc(sizeof(int));
int value = 20;
keycounter = 0;
Head=create(value, keycounter);
value = 30;
insert(value, keycounter);
value = 40;
insert(value, keycounter);
printlist();
delete_list();
free(keycounter);
return 0;
}
// VV functions VV
void delete_list()
{
free(Head);
free(Current);
}
Node* create(int a, int *counter)
{
Node* ptr=malloc(sizeof(Node));
if(!ptr)
{
printf("ERROR-NOT ENOUGH MEMORY\n");
free(ptr);
return 0;
}
ptr->data=a;
ptr->key=*counter;
counter++;
return ptr;
}
void insert(int a, int *counter)
{
Node* ptr=malloc(sizeof(Node));
if(!ptr) {
printf("ERROR-NOT ENOUGH MEMORY\n");
free(ptr);
}
ptr->data=a;
ptr->key=*counter;
//point next field to old head
ptr->next=Head;
//assign current node as head of singly linked list
Head=ptr;
counter++;
}
//Thank you guys over at tutorialspoint for this neat idea for testing this.
//https://www.tutorialspoint.com/data_structures_algorithms/linked_list_program_in_c.htm
void printlist()
{
Node* ptr=Head;
printf("TESTING\n");
while(ptr != NULL) {
printf("%p*NODE* KEY:%i VALUE:%i PTR NEXT:%p\n \n", ptr, ptr->key, ptr->data, ptr->next);
ptr=ptr->next;
}
}
Here is my valgrind output:
Still learning so alot of the valgrind output is pretty arcane to me and threads on stack exchange regarding the "signal 11 (SIGSEGV)" error are difficult to comprehend as well.
Also, any tips or advice on my code would be appreciated.
There is a problem in your code. See the below lines:
int main()
{
int *keycounter =(int*)malloc(sizeof(int));
int value = 20;
keycounter = 0; ===> You are setting the pointer to NULL effectively nullifying the effect of your malloc call above
So, in your create function, when you try to access counter, it is leading to NULL pointer dereference
Node* create(int a, int *counter)
{
Node* ptr=malloc(sizeof(Node));
if(!ptr)
{
printf("ERROR-NOT ENOUGH MEMORY\n");
free(ptr);
return 0;
}
ptr->data=a;
ptr->key=*counter; ==> Here it will lead to NULL pointer dereference
If your key member in the struct is just an integer, then no need to pass a pointer (counter is a pointer), you can as well pass an integer and set it.

Making of linked list by head and node

here's my code in C for making of linked list. Its giving runtime error after the while loop gets executed for one time. Plz help me in correcting my code. (totally confused that where's the error.) I am making a head node first and then adding child nodes to it.
#include <stdio.h>
#include <stdlib.h>
typedef struct node nd;
typedef nd *link;
struct node{
int data;
link next;
};
typedef struct {
int size;
link head;
}list;
void create(link temp)
{
link new;
new=(link)malloc(sizeof(nd));
printf("enter data: ");
scanf("%d",new->data);
temp->next=new;
temp=temp->next;
}
list createlist()
{
list sl;
sl.size=0;
sl.head=0;
return sl;
}
int main()
{
list sl;
sl=createlist();
link temp;
temp=sl.head;
char c;
while (1)
{
printf("Add node?: ");
scanf(" %c",&c);
if (c=='y')
{
create(temp);
sl.size++;
}
else
break;
}
return 0;
}
your createlist() function is returning a reference to a local variable that goes out of scope after it returns. You should instead return a heap based value:
list* createlist() {
list* sl = (list*)malloc(sizeof(list));
sl->size=0;
sl->head=0;
return sl;
}
Initially temp points to NULL. temp = sl.head;
In create(temp) temp->next = new;
You are dereferencing a NULL, address 0x0. I get a segmentation fault when I do that.
Need to change the algorithm.
A debugger shows this problem immediately.
You could use a pointer to pointer for temp. It would be easier to read if you didn't use a typedef for a pointer to node. I haven't tested this, but it should be close:
nd ** create(nd **temp)
{
nd *new;
new=(nd *)malloc(sizeof(nd)); /* this cast shouldn't be needed */
printf("enter data: ");
scanf("%d",&(new->data));
new->next = NULL;
*temp = new;
return &(new->next);
}
/* ... */
int main()
{
nd **temp;
temp = &(sl.head);
/* ... */
temp = create(temp);
/* ... */
}

malloc() causing EXC_BAD_ACCESS error in Xcode

I am trying to implement the Linked List data structure for my college course, but on executing the code the following line produces an EXC_BAD_ACCESS(code=1, address=0x8) error.
temp->next = (ptrtonode) malloc(sizeof(struct node));
Following is the code in its entirety.
#include <stdio.h>
#include <stdlib.h>
typedef struct node *ptrtonode;
typedef ptrtonode header;
struct node
{
int data;
ptrtonode next;
};
ptrtonode create(int n)
{
int i;
header temphead = NULL;
ptrtonode temp = temphead;
for(i=0;i<n;i++)
{
temp->next = (ptrtonode) malloc(sizeof(struct node));
printf("Enter data for node %d: ", i+1);
scanf("%d", &temp->next->data);
temp = temp->next;
}
temp->next = NULL;
return temphead;
}
int main(int argc, const char * argv[])
{
header head;
int n;
printf("How many nodes do you wish to create?");
scanf("%d", &n);
head = create(n);
}
Any help would be appreciated.
Thanks all!
On first iteration of the for loop inside the create() function temp is NULL, which is then dereferenced causing the failure (not malloc() causing the failure). You will need to restructure the code slightly to prevent dereferencing a NULL pointer.
Other points:
casting the return value of malloc() is not required.
check the result of scanf() to ensure n was assigned a valid integer (and confirm that the int is positive):
/* scanf() returns the number of assignments made,
which in this case should be 1. */
if (1 == scanf("%d", &n) && n > 0)
{
/* 'n' assigned a sensible value. */
}

How to allocate memory?

I am trying to create a linked list in my program and I am not able to allocate memory to the structure pointer using malloc(). How do I allocate memory to variables in GCC? The sample program is given below. How to make it work in gcc?
#include<stdio.h>
#include <alloc.h>
struct node
{
int data;
struct node * link;
};
void insert (struct node *p, int d)
{
struct node *temp;
temp = malloc(sizeof(struct node));
temp->data=d;
temp->link=NULL;
if(p==NULL)
{
p=temp;
}
else{
while(p->link!=NULL)
p=p->link;
p->link=temp;
}
}
void disp(struct node *p)
{
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->link;
}
}
int main()
{
struct node *p;
p=NULL;
insert(p,7);
insert(p,9);
disp(p);
}
The error I'm encountering is:
Line 18: error: alloc.h: No such file or directory
In function 'insert':
Line 13: warning: incompatible implicit declaration of built-in function 'malloc'
malloc is in <stdlib.h>. Include that.
Reading the man page for that function would have given you that information. It's not compiler-dependent.
malloc is declared in <stdlib.h>, so that's what you want to #include.
The definition of malloc is in the stdlib.h file:
#include <stdlib.h>
instead of alloc.h.
Like the others say: your error occurs because you have to include stdlib.h instead of alloc.h
To get your list printed, you have to modify p in insert. Currently, you're passing NULL every time you call insert. Change your code that way (pass a pointer-to-pointer to insert):
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node * link;
};
/* note **p instead of *p */
void insert (struct node **p, int d)
{
struct node *temp;
temp = malloc(sizeof(struct node));
temp->data=d;
temp->link=NULL;
if(*p==NULL)
{
*p=temp;
}
else{
while((*p)->link!=NULL)
*p=(*p)->link;
(*p)->link=temp;
}
}
void disp(struct node *p)
{
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->link;
}
}
int main()
{
struct node *p;
p=NULL;
insert(&p,7);
insert(&p,9);
disp(p);
}
and it will print
7
9

Resources