0

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);
}
Nikos
  • 13
  • 5

2 Answers2

0

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.

Community
  • 1
  • 1
Marievi
  • 4,951
  • 1
  • 16
  • 33
0

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.

user3629249
  • 16,402
  • 1
  • 16
  • 17