Мой код обрабатывает деревья бинарного поиска, так что это структуры, на которые я ссылаюсь в коде. Но 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 не указал ни одной строки в код, он выдал эту ошибку, ничего не распечатывая, что заставляет меня думать, что в коде это не так уж далеко.
p.s. Я только что установил GDB и MAKE на мой Mac, получил его с помощью загрузок XCode с сайта разработчика Apple. Так что, возможно, произошла какая-то ошибка в том, как я ее установил.