Home > database >  C Using malloc on a char string
C Using malloc on a char string

Time:12-03

This simplified version of the program has the task of storing a char string in an array. If the product with the given name is already occupied, I don't store it, otherwise I use malloc to allocate space for the chain. But I'm getting a segmentation fault and I can't find the fault Complet program https://onecompiler.com/c/3yqnk3e5s

struct product{
  int *regal;
  char *name;
}product;

struct product allocList(struct product **list, int *alloc)
{
  *list = (struct product*) malloc(sizeof(struct product)*(*alloc));
  (*list)->regal = calloc(100, sizeof(int));
}

int isInList(struct product **list, int *listSize, char *item, int *itemIndex)
{
  for(int i=0; i< *listSize; i  )
    if(! strcmp(item, list[i]->name))
    {
      (*itemIndex) = i;
      return 1;
    }  

  return 0;
}

int insert(struct product **list, int *alloc, int *listSize, char *item, int regalIndex)
{
  int itemIndex = 0; 

  if(isInList(*(&list), *(&listSize), item, &itemIndex))
    return 0;

  list[(*listSize)]->name = (char*) malloc(sizeof(char)*(strlen(item) 1));
  strcpy(list[(*listSize)]->name, item);

  (*listSize)  ;
  return 1;
}

int main()
{

  struct product *list = NULL; int listAlloc = 2000; int listSize = 0; allocList(&list, &listAlloc); 
  
  char *str = "abcd"; char *str1 = "bcd";
  insert(&list, &listAlloc, &listSize, str, 1);
  insert(&list, &listAlloc, &listSize, str, 1);
  insert(&list, &listAlloc, &listSize, str1, 1);

 
  return 0;
}

CodePudding user response:

Your program segfaults in insert() on the first line and when you fix that the following line:

   list[(*listSize)]->name = (char*) malloc(sizeof(char)*(strlen(item) 1));
   strcpy(list[(*listSize)]->name, item);

As list is of type struct product **list it means you deference whatever data is stored sizeof(list) * (*listSize) elements after list which is undefined behavior when *listList > 0. Instead you want to dereference list, then access a array element *listSize. I suggest you use strdup() instead of malloc() strcpy():

    (*list)[*listSize].name = strdup(item);

The next step would be to introduce a struct to hold your list implementation details, and pass that around instead of the double pointers.

  • Related