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

时间:2015-11-14 21:56:10

标签: c graph segmentation-fault gdb valgrind

我正在尝试向我的图形中添加一个新的顶点,它将添加它以便按字母顺序排列。但是,我一直遇到分段错误。我尝试使用调试器和valgrind,但它只告诉我导致seg错误的方法,我的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;

1 个答案:

答案 0 :(得分:5)

这是一个很大的错误

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

这样做:

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