Witiko
Witiko

Reputation: 3387

Why is the following C code being sent a SIGSEGV signal?

I have the following structure:

typedef struct binTree_t {
  int key;
  enum {lMore, rMore, equal} ratio;
  struct binTree_t* parent;
  struct binTree_t*   left;
  struct binTree_t*  right;
  struct binTree_t**  root;
} binTree_t;

which represents an AVL tree. The problem seems to be the root double pointer. The idea is that this way a change to *(node->root) will propagate throughout all nodes pointing to the same node->root. This double abstraction should ensure that **(node->root) always points to the correct root node. However, there seems to be a problem with the way I allocate the memory for it:

binTree_t* createNode(int key, binTree_t* root) {
  binTree_t* node = malloc(sizeof(binTree_t));
  node->key    = key;
  node->ratio  = equal;
  node->parent =
  node->left   =
  node->right  = NULL;
  node->root   = root?&root:&node;
  return node;
}

The following codes both correctly return 12:

int main(void) {
  binTree_t* root = createNode(12, NULL);
  printf("%d", root->key); free(root);
  return EXIT_SUCCESS;
}

int main(void) {
  binTree_t* root = createNode(12, NULL);
  printf("%d", (*(root->root))->key); free(root);
  return EXIT_SUCCESS;
}

The following codes, however, return 12 and 0:

int main(void) {
  binTree_t* root = createNode(12, NULL);
  printf("Text");
  printf("%d", root->key); free(root);
  return EXIT_SUCCESS;
}

int main(void) {
  binTree_t* root = createNode(12, NULL);
  printf("Text");
  printf("%d", (*(root->root))->key); free(root);
  return EXIT_SUCCESS;
}

It looks as though the root->root pointer was allocated on the stack of the createNode function? If so, how do you suggest I repair it, so that it used the mallocated memory?

Upvotes: 0

Views: 125

Answers (1)

unwind
unwind

Reputation: 399871

In createNode(), you're clearly storing the address of a local variable (&node):

node->root   = root?&root:&node;

That won't fly; as soon as that function exits the stored address is invalid and cannot be accessed.

Upvotes: 3

Related Questions