c-分段故障(链表的变体)



当我init_graph然后执行5个add_vertex,然后执行has_vertex时,我遇到了分段错误。

p表示它使用指针

#define SIZE (graph.size)
#define PSIZE (graph->size)
#define NODE (graph.node)
#define PNODE (graph->node)
#define NAME (graph.node[i].name)
#define PNAME (((graph->node)+i)->name)
#define NUM_DEST (graph.node[i].num_dest)
#define PNUM_DEST (((graph->node)+i)->num_dest)
#define DESTCOST (graph.node[i].destcost[j])
#define PDESTCOST (((graph->node)+i)->destcost)
#define DEST_NAME (graph.node[i].destcost[j].dest_name)
#define PDEST_NAME (((((graph->node)+i)->destcost)+j)->dest_name)
#define COST (graph.node[i].destcost[j].cost)
#define PCOST (((((graph->node)+i)->destcost)+j)->cost)

检查图形是否指向非NULL图形并使大小计数器为0

void init_graph(Graph *graph) {
  if (graph != NULL)
    PSIZE = 0;
}

如果不存在,则将new_vertex添加到节点列表中

int add_vertex(Graph *graph, const char new_vertex[]) {

当大小增加1 时,我得到当前大小

  int i = PSIZE++;

如果存在new_vertex,则返回0

  if (has_vertex(*graph, new_vertex))
    return 0;

如果大小不是1,则为另一个节点重新分配空间

否则为节点的大小分配内存

然后添加new_vertex并返回1

  if (PSIZE > 1)
    PNODE = realloc(PNODE, PSIZE * sizeof(node));
  else PNODE = malloc(sizeof(node));
  PNAME = malloc((strlen(new_vertex)+1) * sizeof(char));
  strncpy(PNAME, new_vertex, strlen(new_vertex)+1);
  return 1;
}

检查顶点是否存在

int has_vertex(Graph graph, const char name[]) {
  int i;

检查传入的名称是否为非NULL

  if (name != NULL)

迭代节点列表

    for (i = 0; i < SIZE; i++)

检查是否:当前节点的名称为

如果是:返回1个

      if (strcmp(NAME, name) == 0)
        return 1;
  return 0;
}

很难理解你的代码,而且肯定不可能测试它,因为它是不完整的代码,但我可以怀疑的是:

//[1]
//i gets current size while size increases by 1
    int i = PSIZE++;
//[2]
//if new_vertex exists return 0
    if (has_vertex(*graph, new_vertex))
        return 0;

我认为顺序不正确,无论是否存在new_vertex,您都在增加PSIZE

最新更新