[英]Malloc with pointer tag structure
I am creating a simple graph with nodes and edges. 我正在创建一个包含节点和边的简单图。 I got the functionality going but got some memory bugs.
我得到了功能,但有一些内存错误。
I have a typedef struct in header file: 我在头文件中有一个typedef结构:
typedef struct Graph_s* Graph;
And implementation in c. 并在c中实现。 file:
文件:
struct Graph_s {
Node* nodeArray;
Edge* edgeArray;
size_t edges;
size_t nodes;
};
And function for construction: 和施工功能:
Graph create_graph() {
Graph newGraph = malloc(sizeof(Graph));
newGraph->edges = 0;
newGraph->nodes = 0;
return newGraph;
}
The line Graph newGraph = malloc(sizeof(Graph))
gives: Invalid write of size 8
from Valgrind. Graph newGraph = malloc(sizeof(Graph))
给出:Valgrind Invalid write of size 8
。
malloc(sizeof(Graph))
is only allocating enough memory for a pointer. malloc(sizeof(Graph))
仅为指针分配足够的内存。 Change it to malloc(sizeof(struct Graph_s))
. 将其更改为
malloc(sizeof(struct Graph_s))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.