简体   繁体   中英

Segmentation fault (core dumped) while running the program

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM