[英]Value of struct variable changes after malloc of other variable of same struct
So i am trying to initiliaze a node of a graph. 所以我试图初始化一个图的节点。 The problem is that the value of the variable
node->edges_capacity
changes from 2 to some random int for no apparent reason, at least to my knowledge. 问题是,至少在我所知的范围内,变量
node->edges_capacity
值从2更改为某个随机int并没有明显的原因。
Moreover, when i use the debug mode of CLion, it prints 2 as expected! 而且,当我使用CLion的调试模式时,它会按预期打印2!
Am i doing something wrong with malloc
? 我对
malloc
做错了吗?
typedef struct node {
int id;
int degree;
int edges_capacity;
struct node **edges;
} Node;
Node *node_create(int id) {
Node *node = (Node *) malloc(sizeof(Node *));
if (node == NULL)
exit(1);
node->id = id;
node->degree = 0;
node->edges_capacity = 2;
node->edges = (Node **) malloc(node->edges_capacity * sizeof(Node *));
node_debug(node); // prints a random int for node->edges_capacity instead of 2
return node;
}
void node_debug(Node *node) {
printf("id:%d degree:%d capacity:%d\n", node->id, node->degree, node->edges_capacity);
}
Change this line : 更改此行:
Node *node = (Node *) malloc(sizeof(Node *));
to : 至 :
Node *node = malloc(sizeof(Node));
as you declare node
to be a pointer to type Node
, and not to Node *
. 当您声明
node
为指向Node
类型而不是Node *
的指针时。
Also, see this link on why not to cast the result of malloc
. 另外,请参见此链接 ,了解为什么不
malloc
的结果。
this line: 这行:
Node *node = (Node *) malloc(sizeof(Node *));'
has a couple of problems. 有几个问题。
Node
, not a pointer to a Node
. Node
分配足够的空间,而不是pointer to a Node
的pointer to a Node
。 void*
, which can be assigned to any other pointer. void*
,可以将其分配给任何其他指针。 Casting the returned value just clutters the code, making int much more difficult to understand, debug, maintain. The following, posted code is writing to areas in the heap memory that the program does not own. 以下发布的代码正在写入程序不拥有的堆内存中的区域。 This is undefined behavior and can lead to a seg fault event.
这是未定义的行为,可能导致段故障事件。 Your noticing one aspect of that undefined behavior.
您注意到该未定义行为的一个方面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.