gcc 如何修复C代码中的SIGSEGV(分段错误)?

t30tvxxf  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(139)

我正在用C编写一个程序,它读取文件中用括号分隔的句子,将它们解释为“rooms”(不要问),并将它们作为动态分配的节点附加到动态分配的单链表结构中。

current->next = createnode(room);

字符串
行为一导致SIGSEGV(地址边界错误)
代码如下:

void
create_room(char *text, list *list)
{
  unsigned int index;
  color_t color;
  char *description;

  parse_curly_brackets(text, &index, &color);

  room_t *new_room = (room_t *)malloc(sizeof(room_t));
  new_room->index = index;
  new_room->color = color;

  char *ptr = strchr(text, '}');
  if (ptr != NULL)
    {
      ptr = strchr(ptr + 1, '}');
      if (ptr != NULL)
        {
          ptr++; 
          while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\n')) 
            ptr++;

          description = ptr;
          new_room->description = (char *)malloc(strlen(description));
          strcpy(new_room->description, description);
        }
      else
        {
          printf("Second closing curly brace not found\n");
          free(new_room);
          return;
        }
    }
  else
    {
      printf("Closing curly brace not found\n");
      free(new_room);
      return;
    }

  add_to_list(new_room, list);
}

node_t
*createnode (const room_t *room)
{
  node_t *newnode = malloc(sizeof(node_t));

  if (!newnode)
    {
      return NULL;
    }
  
  newnode->data = room;
  newnode->next = NULL;

  return newnode;
};

void
add_to_list (const room_t *room, list *list)
{
  node_t *current = NULL;

  if (list->head == NULL)
    {
      list->head = createnode(room);
    }

  else
    {
      current = list->head;
      while (current->next != NULL)
        {
          current = current->next;
        }
      current->next = createnode(room);
    }
}


以下是结构:

typedef
struct List
{
  struct Node *head;
  
} list;

typedef
struct Node
{
  const struct Room *data;
  struct Node *next;
} node_t;

typedef
struct Room
{
  unsigned int index;
  color_t color;
  list objects;
  char *description;  /* the description buffer that will be written from the file */
  
} room_t;


我尝试将一些函数参数设置为const以提供只读访问,但我不确定是否使情况变得更糟。我已经检查了是否正确分配了内存,但我找不到导致问题的原因。所以我希望你会!你可以在这里熟悉完整的代码:https://github.com/stakhovyak/agorica你可以检查description.org文件以了解我在create_room函数中尝试做什么。

djmepvbi

djmepvbi1#

您不为null终结符分配空间:

new_room->description = (char *)malloc(strlen(description));
          strcpy(new_room->description, description);

字符串
您需要再分配一个字节:

new_room->description = malloc(strlen(description) + 1);
          strcpy(new_room->description, description);


另外,不要强制转换malloc的结果。

相关问题