【发布时间】:2012-03-15 21:05:49
【问题描述】:
我的代码处理二叉搜索树,所以这些是我在代码中引用的结构。但是 gdb 似乎在运行我的任何代码之前就崩溃了。
/* 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);
}
在 gdb 中运行它会导致以下崩溃:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x000000000000000c
0x0000000100000cc8 in main ()
如果我只是运行代码,它会通过 main() 中的第一个打印语句,但在调用 count_nodes 时崩溃,所以我认为这是一些奇怪的指针错误,但 gdb 没有指出任何行代码,它给了e那个错误而没有打印出任何东西,这让我觉得它在代码中并没有走得太远。
附言我只在我的 Mac 上安装了 gdb 和 MAKE,从苹果的开发者网站下载了 Xcode。所以我的安装方式可能有一些错误。
【问题讨论】:
标签: c tree gdb binary-tree