c - 段错误(链表的变体)

标签 c segmentation-fault

当我 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[]) {

i 获取当前大小,同时大小增加 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

关于c - 段错误(链表的变体),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470236/

相关文章:

PHP 扩展 : How to return a new class object

iPhone KERN_INVALID_ADDRESS

c - 为什么 feof() 中会出现段错误?

c - 从共享内存读取段错误

Ruby 1.8.6 `gem install` 段错误与 "abort trap 6"

c - 这个 C99 IS_LITTLE_ENDIAN 宏可移植吗?

c - Firebird 的 gpre 工具为 gds__null 创建了一个静态定义 - 如何摆脱 'defined but not used' 编译器警告?

c - 为什么可以将 () 写入 STDIN?

C - 解析任意图像文件

c++ - 信号名称 : SIGSEGV error