【问题标题】:Initialized a struct variable to NULL, but it isn't null when called将结构变量初始化为 NULL,但在调用时它不为 null
【发布时间】:2017-10-15 18:11:25
【问题描述】:

我必须根据一些特定的准则制作一个带有函数的图形数据类型。

我必须有一个初始化空图的函数。在这个函数中,我将第一个顶点设置为 NULL。只是测试一下,我运行我的 num_vertices 方法,我得到一个分段错误。它应该返回 0。

在我自己的调试之后,我了解到,在对新图调用 init 函数之后,调用 num_vertices 函数以某种方式传递了一个不为 NULL 的顶点,即使 init 函数将其设置为 NULL。因此,我的 num_vertices 方法会遍历为我的图分配的所有内存,直到遇到 seg 错误。

为什么会发生这种情况,如何将其设置为 NULL 以便我的 num_vertices 工作?

我的图形结构(需要做类似这样):

typedef struct Edge Edge;
typedef struct Vertex Vertex;
typedef struct Graph Graph;

struct Graph {
    Vertex *vertex;
};

struct Vertex {
    /* use a tree to store vertices */
    Vertex *left;
    Vertex *right;

    char *name;
    Edge *edge; /* the edge between this vertex and its root */
};

struct Edge {
    unsigned int cost;
};

我的 init_graph() 和 num_vertices():

void init_graph(Graph *graph) {
    graph = (Graph *)malloc(sizeof(Graph));
    graph->vertex = NULL;
}

int num_vertices(Graph graph) {
    return count_vertices(graph.vertex);
}

int count_vertices(Vertex *vertex) {
    int count = 0;
    if (vertex != NULL) {
        count += count_vertices(vertex->left);
        count++;
        count += count_vertices(vertex->right);
    }
    return count;
}

最后,我用来测试的代码出现了段错误:

int main() {
    Graph graph;

    init_graph(&graph); /* initialize new graph */

    assert(num_vertices(graph) == 0); /* seg fault here */

    printf("It all worked!\n");
    return 0;
}

【问题讨论】:

  • 你为什么要首先分配内存给graph->vertex然后然后NULL覆盖那个set指针?!
  • (Graph** graph) and *graph = malloc(...) 或者,返回一个图表*
  • 这些片段如何编译? int num_vertices(Graph graph) 应该是 int num_vertices(struct Graph graph)。请发布显示问题的Minimal, Complete, and Verifiable example
  • @WeatherVane malloc 中的演员表 - 我怀疑这是 C++..
  • 它用 C++ 编译 :))

标签: c struct segmentation-fault


【解决方案1】:

您分配了一个Graph 将其地址传递给一个函数,该函数通过一个指针来操作它,您在该指针中存储动态分配的内存块,因此您不会更改原始变量中的任何内容。这是无稽之谈。只需初始化结构,如下所示:

void init_graph(Graph *graph) {
    graph->vertex = (Vertex *)malloc(sizeof(Vertex));
    graph->vertex = NULL;
}

请注意,您的代码不是有效的 C,除非您键入定义的 Graph。

【讨论】:

  • 非常感谢,这已解决!我假设我必须为 Graph 结构本身及其内部组件动态分配内存。为什么不是这样?此外,这些结构是类型定义的,我只是从我的 OP 中省略了它;我已经添加了它。
  • 这只是内存泄漏。
  • @shplaz 并非如此,因为写入Graph graph 已经为 Graph 对象分配了内存!了解变量和指针。
猜你喜欢
  • 1970-01-01
  • 2016-08-17
  • 2013-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
相关资源
最近更新 更多