【问题标题】:Malloc breaks functionMalloc 中断函数
【发布时间】:2022-01-21 05:11:48
【问题描述】:

我有一个问题,我的 malloc 破坏了我的程序。删除它会使其工作,但我需要它进一步。有人可以解释我做错了什么。提前致谢!!

我的graph.c中有这个函数

bool graph_initialise(graph_t *graph, unsigned vertex_count)
    {
      assert(graph != NULL);
        graph = (struct graph_s*) malloc(sizeof(struct graph_s));
        if (graph == NULL){return true;}
        graph->vertex_count = vertex_count;

        graph->adjacency_lists = (struct adjacency_list_s*) malloc(vertex_count * sizeof(struct adjacency_list_s));
        if (graph->adjacency_lists == NULL){
        return true;
        }

        int i;
        for (i = 1; i < vertex_count; ++i){
        graph->adjacency_lists[i].first = NULL;
        }
      return false;

这在我的graph.h中

typedef struct edge_s
{
  /* Points to the next edge when this edge is part of a linked list. */
  struct edge_s *next;

  unsigned tail;    /* The tail of this edge. */
  unsigned head;    /* The head of this edge. */
  unsigned weight;  /* The weight of this edge. */
} edge_t;

typedef struct adjacency_list_s
{
  edge_t *first; /* Pointer to the first element of the adjacency list */
} adjacency_list_t;

/* Type representing a graph */
typedef struct graph_s
{
  unsigned vertex_count; /* Number of vertices in this graph. */
  unsigned edge_count;   /* Number of edges in this graph. */

  /* Pointer to the first element of an array of adjacency lists. The array
   * is indexed by vertex number
   */
  adjacency_list_t *adjacency_lists;
} graph_t;

【问题讨论】:

  • 破坏程序是什么意思?消息是什么?
  • 断言很奇怪,你为什么关心它是否为空,下一行覆盖它,如果有的话我会认为它应该为空
  • 你也将在这里泄漏,你分配了内存但是当你返回时丢失了指向它的指针。一旦此函数退出,更改函数中的“图形”就不会做任何事情。我怀疑你需要 **graph 作为参数
  • 另外,您不需要命名结构。让结构保持匿名并改用定义的类型,就像adjacency_list_t 而不是struct adjacency_list_s。这里的冗余太多了。

标签: c graph initialization malloc


【解决方案1】:

我怀疑这个问题是您希望此函数为您分配 grph,然后从调用代码对分配的图进行操作(您不显示调用代码)

即你正在做类似的事情

graph *gptr;
graph_initialise(gptr,42);
printf("vc = %d", gptr->vertex_count);

问题是 grpah_initialize 没有设置 gptr。你需要

bool graph_initialise(graph_t **gptr, unsigned vertex_count)
    {
        *gptr = (struct graph_s*) malloc(sizeof(struct graph_s));
        graph_t *graph = *gptr;
        if (graph == NULL){return true;}
        graph->vertex_count = vertex_count;

        graph->adjacency_lists = (struct adjacency_list_s*) malloc(vertex_count * sizeof(struct adjacency_list_s));
        if (graph->adjacency_lists == NULL){
        return true;
        }

        int i;
        for (i = 1; i < vertex_count; ++i){
        graph->adjacency_lists[i].first = NULL;
        }
      return false;

然后这样称呼它

graph *gptr;
graph_initialise(&gptr,42);
printf("vc = %d", gptr->vertex_count);

for 循环也应该从 0 而不是 1 开始

【讨论】:

    猜你喜欢
    • 2015-08-03
    • 2017-04-04
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    相关资源
    最近更新 更多