#include<stdio.h>
#include<string.h>
#include<malloc.h>
//#include<conio.h>
struct list
{
char *value;
struct list *link;
};
struct list *arr[12];int val;
int hf(char *item)
{
int sum,i=0;
while(item[i]!='\0')
{
sum+=item[i];
i++;
}
return sum%12;
}
void insert(struct list ** arr,char *item,int val)
{
struct list *temp,*r;
r=*arr;
temp=(struct list *)malloc(sizeof(struct list));
strcpy((temp->value),item);
if(strcmp((r->value),NULL))
{
strcpy((r->value),(temp->value));
(r->link)=NULL;
}
else
{
while(r->link!=NULL)
r=r->link;
r->link=temp;
r=r->link;
strcpy((r->value),(temp->value));
r->link=NULL;
}
*arr=r;
}
void main()
{
struct list *li[12];int i=0;
for(i=0;i<12;i++)
{
li[i]=NULL;
}
char *item;int ret;
strcpy(item,"Steve");
ret=hf(item);
insert(&li[ret],item,ret);
strcpy(item,"raj");
ret=hf(item);
insert(&li[ret],item,ret);
strcpy(item,"Notes");
ret=hf(item);
insert(&li[ret],item,ret);
}
The above program is to implement array of linked list and im trying to insert string
as the value. When i am trying to run the program, there are no errors but it tells segmentation fault(core dumped)
so please explain the reason
The code
char *item;int ret;
strcpy(item,"Steve");
tries to copy the string literal "Steve" to an uninitialised pointer. You need to allocate memory for item. The easiest way of doing this is to hard-code a suitably sized stack buffer
char item[50];
You also have a similar problem inside insert. You could solve this in the same way
struct list
{
char value[50];
struct list *link;
};
or you could dynamically allocate the correct size of buffer inside insert
temp->value = malloc(strlen(item) + 1);
if (temp->value == NULL) {
/* handle oom error */
}
strcpy(temp->value, item);
In this latter approach, make sure to free(node->value) when you free that list node. Note also that freeing of all dynamically allocated memory is currently missing from your program, meaning that you leak all memory allocated using malloc.
There is one more bug in your code - insert assumes that arr is a pointer to a valid list* but it is always NULL. You need to update either main or the assumption in insert here.
change the following
In insert() function change the if loop
if(r==NULL){
r = temp;
}
Change the structure. change the size of the structure for your need
struct list
{
char value[25];
struct list *link;
};
Change the variable item to
char item[25];
EDIT :
There is no need to typecast the output of malloc
Related
I was trying to implement circular queue functionality. I am a C++ coder and I found it surprising that in C, struct cannot have member functions. Anyway this is my implementation:-
#include <stdio.h>
#include <stdlib.h>
struct node
{
int nvalue;
struct node *next;
};
struct CLlist
{
struct node* head;
struct node* tail;
int size;
};
void insert(struct CLlist *l,int num)
{
struct node *n=malloc(sizeof(struct node));
n->nvalue=num;
n->next=NULL;
if((l->head==l->tail)==NULL)
{
l->head=l->tail=n;
}
else if(l->head==l->tail && l->head!=NULL)
{
l->head->next=n;
l->tail=n;
l->tail->next=l->head;
}
else
{
l->tail->next=n;
l->tail=n;
l->tail->next=l->head;
}
l->size++;
}
void print(struct CLlist *l)
{
int idno=1;
printf("printing the linked list with size as %d\n",l->size);
struct node *cptr;
for(cptr=(l->head);cptr!=(l->tail);cptr=cptr->next)
{
printf("The idno is %d and the number is %d\n",idno,cptr->nvalue);
idno++;
}
//this is to print the last node in circular list : the tail node
idno++;
cptr=cptr->next;
printf("The idno is %d and the number is %d\n",idno,cptr->nvalue);
}
int main()
{
struct CLlist a;
struct CLlist *l;
l=&a;
insert(l,2);
insert(l,5);
insert(l,7);
insert(l,10);
insert(l,12);
print(l);
return 0;
}
I get segmentation fault in the line
printf("The idno is %d and the number is %d\n",idno,cptr->nvalue);
why does the error occur? I guess I am not passing l by pointer by value (passing pointers as by value) properly. could somebody help me in pointing out where I am going wrong?
Thanks
You never initialize the variable a in the main function, so its contents is indeterminate and using the members of that structure will lead to undefined behavior.
Your code has two issues, the first one more serious.
Your first issue is that the head and tail members of your CLlist structure are not being initialized to NULL, which can (non-deterministically) keep any real data from being stored in your structure. This can be fixed by adding the following 2 lines in main just before the first insert call:
l->head = NULL;
l->tail = NULL;
Your second problem is in this line:
if((l->head==l->tail)==NULL)
While it looks like this is comparing both l->head and l->tail to NULL, it's actually comparing l->head to l->tail, and then comparing that boolean result to NULL, which is effectively 0. The line should be changed to:
if((l->head == NULL) && (l->tail == NULL))
This will individually test both the head and tail pointers, and will only take that branch if they are both NULL.
You have a pointer
struct node *cptr;
// You're probably trying to access an unassigned pointer head in the next step
for(cptr=(l->head);cptr!=(l->tail);cptr=cptr->next)
As per the standards, there is no requirement that
a->head & a->tail are initialized to NULL
when you did
struct CLlist a;
Standard ISO/IEC 9899:201x clause 6.7.9->10 states
If an object that has automatic storage duration is not initialized
explicitly, its value is indeterminate.
In fact you're:
struct CLlist a;
// missing something here.
struct CLlist *l;
l=&a;
typedef struct Node
{
void ** pointers;
Value ** keys;
struct Node * parent;
bool is_leaf;
int num_keys;
struct Node * next;
} Node;
typedef struct ScanManager {
int keyIndex;
int totalKeys;
Node * node;
} ScanManager;
I am getting an error "Segmentation fault (core dumped)" when I try to allocate memory for my structure ScanManager. I am writing -
ScanManager * scanmeta = (ScanManager *) malloc(sizeof(ScanManager));
I have tried using calloc instead of malloc but that didn't work. How do I allocate memory for that structure since I want to use it further in my code?
typedef struct Value {
DataType dt;
union v {
int intV;
char *stringV;
float floatV;
bool boolV;
} v;
} Value;
Also, I have one more structure -
typedef struct BT_ScanHandle {
BTreeHandle *tree;
void *mgmtData;
} BT_ScanHandle;
I am passing this structure's reference in a function as mentioned below and try to access my ScanManager structure here -
openTreeScan(BT_ScanHandle **handle)
{
struct ScanManager *scanmeta = malloc (sizeof (struct ScanManager));
(** handle).mgmtData = scanmeta;
/* Remaining code */
}
I finally figured out the error. It was not in allocating space to ScanManager. Instead, I was trying to initialize some of the members of BT_ScanHandle structure without allocating memory space to itself. The working code is -
openTreeScan(BT_ScanHandle **handle)
{
struct ScanManager *scanmeta = malloc(sizeof(ScanManager));
*handle = malloc(sizeof(BT_ScanHandle)); //Allocating some space
(*handle)->mgmtData = scanmeta; // Initializing
/* Remaining code */
}
I have just started using pointers.So please bear with me if this looks silly
But I am not able to find the reason.
I have a structure
typedef struct Intermediatenode
{
int key;
char *value;
int height;
struct node *next[SKIPLIST_MAX_HEIGHT];
} node;
And I wand to create a new node by using below function
node *create_node(int key, char * val, int h)
{
node *newnode;
newnode=malloc(sizeof(node));
newnode->height=h;
newnode->key=key;
printf("till here %s \n",val);
printf("till here %d \n",newnode->height);
printf("till here %d \n",newnode->key);
strcpy(newnode->value,val);
printf("till here %s \n",newnode->value);
return newnode;
}
But I Am getting segmentation fault at this
"strcpy(newnode->value,val);"
Can you please help me with that.Thanks a lot
You allocated memory for the node, but not the string in value. The strcpy function will copy bytes but not allocate memory. It assumes that you've already arranged that. In a pinch, you can allocate and copy the string with strdup:
newnode->value = strdup(val);
i Wrote a queue in c
and in the function remove when i tring to free the memory of the node the program crashes.
this is the code of the function remove:
int RemoveFromQueue(Queue a)
{
int r=0;
printf("test0\n");
if(a->First!=NULL)
{
printf("test1\n");
a->Length=a->Length-1;
r=a->First->DATA;
NodeQ tmp=a->First;
printf("test2\n");
if(tmp==a->Last)
{
a->Last=NULL;
}
printf("test3\n");
a->First=a->First->next_Node;
printf("test4\n");
free(tmp);
printf("test5\n");
}
else
{
return NULL;
}
return r;
}
the code of queue:
struct NodeQ_s{
int DATA;
struct NodeQ_s *next_Node;
};
struct Queue_s{
int Length;
NodeQ First;
NodeQ Last;
};
.h file:
typedef struct NodeQ_s *NodeQ;
typedef struct Queue_s *Queue;
insert function:
void InsertToQueue(Queue a,int b)
{
if(a->First==NULL)
{
a->Length=1;
a->First=malloc(sizeof(*(a->First)));
a->First->DATA=b;
a->First->next_Node=NULL;
}
else
{
a->Length=a->Length+1;
NodeQ tmp=malloc(sizeof((*tmp)));
tmp->DATA=b;
if(a->Last==NULL)
{
a->Last=tmp;
a->First->next_Node=a->Last;
}
else
{
a->Last->next_Node=tmp;
a->Last=a->Last->next_Node;
a->Last->next_Node=NULL;
}
}
}
can you tell me what i did wrong or why it crashes?
It is crashing because you're trying to free dynamic memory that doesn't even exist!
free takes a pointer to a memory location that it's supposed to deallocate, and you're passing it a NodeQ object. You see where the problem lies ?
If a->First is a malloc'd pointer you want to free then I guess that you want to point to it, not create a copy of it like you did. Like this:
NodeQ *tmp = a->First;
Then you can free it.
OfCourse if a->First isn't a malloc'd pointer then you don't have call free.
Edit
After seeing your struct definition, First isn't even a pointer! You can't call malloc for it.
Or you can get what's stored in there using the dereferencing operator like this: *malloc and when you're freeing it, get its address, like this: free(&a->First)
Below is the C program I have written. It contains an implementation of the doubly linked list.
#include <stdio.h>
/* node of a doubly linked list */
typedef struct _dlnode {
struct _dlnode* prev;
int key;
struct _dlnode* next;
} dlnode;
/* doubly linked list */
typedef struct _dllist {
dlnode* head;
dlnode* tail;
} dllist;
/* returns an empty doubly linked list */
dllist* empty_dllist () {
dllist* l;
l->head=NULL;
l->tail=NULL;
return l;
}
int main()
{
dllist* l;
l=empty_dllist ();
return 0;
}
I get the following runtime error:
Segmentation fault: 11
What is it caused by?
You have to allocate memory for a structure before you use a pointer to it to access its members. Change your function empty_dllist to -
dllist *empty_dllist(void) {
dllist *l = malloc(sizeof *l);
if(l == NULL) {
// failed to allocate memory
// handle it
// return NULL
}
l->head = NULL;
l->tail = NULL;
return l;
}
A segmentation fault is usually caused by trying to follow an uninitialized or NULL pointer.
In your program, you have pointer variable l in the function empty_dllist, and you try to follow that pointer to what it points to. But the variable is uninitialized, and cointains garbage, so it is not surprising that you get a segmentation fault.
You probably want to add a call to malloc in empty_dllist, to allocate a header struct for your list.
You are not allocating memory:
dllist* l = malloc(sizeof(dllist));
so trying to access l->head causes error memory access