简体   繁体   中英

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.

Moreover, when i use the debug mode of CLion, it prints 2 as expected!

Am i doing something wrong with 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 * .

Also, see this link on why not to cast the result of 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 .
  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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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