【发布时间】: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