【问题标题】:GDB error I don't recognize: "Program received signal EXC_BAD_ACCESS"我不认识的 GDB 错误:“程序收到信号 EXC_BAD_ACCESS”
【发布时间】: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


    【解决方案1】:

    您不会从bst_create() 返回tree。您的程序会导致未定义的行为 - 任何事情都可能发生。你应该打开一些警告。

    抛开社论:不要在 C 程序中强制转换 malloc() 的返回值。

    【讨论】:

    • 强制转换 malloc 是不好的做法吗?为什么?
    • 假设您忘记了#include <stdlib.h>。通常会发出有关类型转换的警告,但您的类型转换将使所述警告静音。
    【解决方案2】:

    您忘记返回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;
    }
    

    【讨论】:

      【解决方案3】:
      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;
      }
      

      使用a会更好

      return tree;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-17
        • 2010-09-24
        • 2023-03-09
        • 2012-10-05
        相关资源
        最近更新 更多