Mingw对struct使用malloc
我刚刚在作业中遇到了一个malloc问题 //这是我的头文件Mingw对struct使用malloc,c,struct,malloc,C,Struct,Malloc,我刚刚在作业中遇到了一个malloc问题 //这是我的头文件 struct vertex_t { int id; char *label; /* A list of vertices representing incoming edges */ List in; /* A List of vertices representing outgoing edges */ List out; }; struct graph_t { /* Num
struct vertex_t {
int id;
char *label;
/* A list of vertices representing incoming edges */
List in;
/* A List of vertices representing outgoing edges */
List out;
};
struct graph_t {
/* Number of vertices */
int order;
/* Numb er of edges */
int size;
Vertex vertices;
};
//我们不允许更改上面的头文件。在我的主文件中,如何对图形中的顶点进行malloc
Graph new_graph(int order) {
Graph graph;
int i;
graph=NULL;
graph=(Graph)malloc(sizeof(Graph));
assert(graph);
graph->order=order;
graph->size=0;
graph->vertices=(Vertex*)malloc((order+100000)*sizeof(Vertex));//!!!!!!!!!!!!!!!!!!!this line!!!!
for(i=0;i<order;i++){
graph->vertices[i].label=(char*)malloc(MAX_LINE_LEN*sizeof(char));
graph->vertices[i].in=NULL;
graph->vertices[i].out=NULL;
}
return graph;
}
Graph新图形(整数顺序){
图形;
int i;
图形=空;
图=(图)malloc(sizeof(图));
断言(图);
图形->顺序=顺序;
图形->大小=0;
图形->顶点=(顶点*)malloc((订单+100000)*大小(顶点));/!!!!
对于(i=0;ivertices[i]。label=(char*)malloc(MAX_LINE_LEN*sizeof(char));
图->顶点[i]。in=NULL;
图->顶点[i]。out=NULL;
}
返回图;
}
我只能在malloc中添加非常大的数字以防止内存泄漏。很难看到所有错误,因为您没有给出完整的程序,但据我所知,您在这行代码中出错了:
graph=(Graph)malloc(sizeof(Graph));
graph->vertices=(Vertex*)malloc((order+100000)*sizeof(Vertex));
图形
和顶点
似乎是指针类型,因此您应该改为:
graph = malloc(sizeof(struct graph_t));
graph->vertices = malloc((order)*sizeof(struct vertex_t));
我假设Vertex
是与struct Vertex\u t
关联的指针类型,Graph
是与标题中的struct Graph\u t
关联的指针类型
我们不使用malloc()
为指针本身分配内存,而是为指针指向的数据分配内存。因此大小取决于数据。如果pType
是指针类型,例如char*
,int*
或struct my_struct*
,sizeof(pType)
将始终是相同的(例如,32位程序为8,64位程序为16)
这是第一个问题。请遵循正确的模式:
struct Foo { ... };
Foo* foo = malloc(sizeof(Foo)); // one way
foo = malloc(sizeof(*foo)); // the other way, handy when you are not sure what your type is
请注意如何传入结构的大小并返回指针
第二次分配也会发生同样的情况:
graph->vertices = (Vertex*)malloc((order+100000)*sizeof(Vertex));
在代码中,Graph
和Vertex
都是指针,但您希望将指针分配给结构,而不是指针
此外,您将结果强制转换为
Vertex*
,但将其分配给Vertex
。这应该会引发编译器警告。您必须阅读、理解并消除所有警告,没有例外。我建议您设置编译器,使其将警告视为错误。不是答案,而是类似graph=(graph)malloc(sizeof(图));
和其他。什么是类型顶点
?顶点的类型定义
在哪里?伟大的思想都是一样的…列表是什么?看看使用realloc。
graph->vertices = (Vertex*)malloc((order+100000)*sizeof(Vertex));