gpt4 book ai didi

c - 为什么我的代码返回段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 05:53:21 24 4
gpt4 key购买 nike

我正在尝试向我的图表添加一个新顶点,该顶点将添加它以便按字母顺序排列。但是,我一直遇到段错误。我尝试使用调试器和 valgrind,但它只告诉我是什么方法导致了段错误,我的 add_vertex。

    /* Adds a vertex with element new_vertex */
int add_vertex(Graph *graph, const char new_vertex[])
{
Vertex *new, *curr = graph -> vertices, *prev;
if ( has_vertex (*graph, new_vertex) || graph == NULL)
return 0;
for (prev = graph->vertices; curr = prev->next; prev = curr)
if (curr->element > new_vertex)
break;
new = malloc ( sizeof ( Vertex ) );
new->element = ( char *) malloc ( sizeof ( strlen ( new_vertex ) + 1) );
strcpy ( new -> element, new_vertex );
graph -> counter++;
/* Adds a vertex to the graph */
if (curr != NULL) {
/* Case 1 or 2: Vertex not at end of the graph */
if (prev != graph -> vertices) { /* Case 1: not at front */
new -> next = curr;
prev -> next = new;
}
else { /* case 2: at front */
new -> next = curr;
graph -> vertices -> next = new;
}

}
else /* Case 3 or 4: at the end of the graph */
if (prev != graph -> vertices){ /* Case 3: not at front */
new -> next = NULL;
prev -> next = new;
}
else{ /* Case 4: at front */
new -> next = NULL;
graph -> vertices -> next = new;
}


return 1;
}

这是我如何实现我的图表

#if !defined(GRAPH_IMPLEMENTATION_H) 
#define GRAPH_IMPLEMENTATION_H
#include <string.h>
#include <stdio.h>


typedef struct edge
{ int cost;
char* symbol;
} Edge;

typedef struct vertex
{ struct vertex *next;
char* element;
struct edge *connect;
int counterE;
} Vertex;

typedef struct graph
{ Vertex* vertices;
int counter;
} Graph;

最佳答案

这里是个大错误

new -> element = ( char *) malloc ( sizeof ( strlen ( new_vertex ) + 1) );
// ^^^^^

只需这样做:

new -> element =  malloc (  strlen ( new_vertex ) + 1 );

关于c - 为什么我的代码返回段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33713861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com