My code handles Binary Search Trees, so those are the structures I a referencing in the code. But gdb seems to crash before running through any of my code.
/* my own recursive function, counts number of nodes in tree */
int count_nodes(bst_node_t *node)
{
if( node == NULL )
return 0;
/* if this is a leaf, return 1 */
if( node->left == NULL && node->right == NULL )
return 1;
/* if left side empty, return 1 + count for right subtree */
else if( node->left == NULL )
return 1 + count_nodes(node->right);
/* if right side empty, return 1 + count for left subtree */
else if( node->right == NULL )
return 1 + count_nodes(node->left);
/* otherwise, return 1 + count for both left and right subtrees */
else
return 1 + count_nodes(node->left) + count_nodes(node->right);
}
/* mallocs the header for the BST, initializes it, and returns pointer to it */
bst_t *bst_create (void)
{
bst_t *tree = (bst_t *)malloc(sizeof(bst_t));
tree->root = NULL;
tree->tree_size = 0;
tree->num_recent_key_comparisons = 0;
}
int main(void)
{
bst_t *tree = bst_create();
printf("size = %d, comparisons = %d\n", tree->tree_size, tree->num_recent_key_comparisons);
printf("size from count_nodes = %d\n", count_nodes(tree->root));
free(tree);
}
Running this in gdb gets me the following crash:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x000000000000000c
0x0000000100000cc8 in main ()
If I just run the code, it gets through the first print statement in main(), but crashes on the call to count_nodes, so I thought it was some odd pointer error, but gdb didn't point out any line in the code, it gave e that error without printing anything out, which makes me think it didn't get far in the code.
ps I only JUST installed gdb and MAKE on my mac, got it with the Xcode downloads from apple's developer website. So there may have been some error with how I installed it.
You're not returning tree
from bst_create()
. Your program causes undefined behaviour - anything could happen. You should turn some warnings on.
Editorial aside: Don't cast the return value of malloc()
in a C program.
bst_t *bst_create (void)
{
bst_t *tree = (bst_t *)malloc(sizeof(bst_t));
tree->root = NULL;
tree->tree_size = 0;
tree->num_recent_key_comparisons = 0;
}
would work better with a
return tree;
You forgot to return the node in your bst_create
bst_t *bst_create (void)
{
bst_t *tree = (bst_t *)malloc(sizeof(bst_t));
tree->root = NULL;
tree->tree_size = 0;
tree->num_recent_key_comparisons = 0;
return tree;
}
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.