简体   繁体   English

结构变量的值在相同结构的其他变量的malloc之后更改

[英]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. 有几个问题。

  1. need to be allocating enough room for the full size of a Node , not a pointer to a Node . 需要为整个Node分配足够的空间,而不是pointer to a Nodepointer to a Node
  2. when call any of the heap allocation functions (malloc, calloc, realloc) the returned type is void* , which can be assigned to any other pointer. 当调用任何堆分配函数(malloc,calloc,realloc)时,返回的类型为void* ,可以将其分配给任何其他指针。 Casting the returned value just clutters the code, making int much more difficult to understand, debug, maintain. 强制转换返回值只会使代码混乱,使int更加难以理解,调试和维护。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM