【问题标题】:Why is my code returning a segmentation fault?为什么我的代码返回分段错误?
【发布时间】:2016-02-16 06:44:59
【问题描述】:

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

【问题讨论】:

  • if ( has_vertex (*graph, new_vertex) || graph == NULL)?想想你做了什么。
  • 加到@EOF:最有可能的评估顺序是从左到右。
  • 是否应该在最后一个 else 周围放置大括号?
  • OT:在 C 语言中也不需要强制转换 "malloc() & Friends",也不建议以任何方式使用。保持一致。
  • @alk:没有什么“可能”。 C11 标准草案,6.5.14 Logical OR operator, Section 4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation;

标签: c graph segmentation-fault gdb valgrind


【解决方案1】:

这里有个大错误

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

这样做:

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

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多