【问题标题】:Freeing dynamically allocated memory in a tree释放树中动态分配的内存
【发布时间】:2013-04-14 19:45:28
【问题描述】:

我正在尝试释放我用 malloc 分配的内存,但 free 给出了错误:

 malloc: *** error for object 0x100100800: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap

我有一棵带节点的树

struct node {
  struct state *s;
  struct node *child;
  struct node *sibling;
};

我正在尝试使用此功能释放除一个孩子及其死者以外的所有节点:

struct node * free_children (struct node *head, struct node *keep_c) {
  struct stack_node *stack_head = init_stack();
  struct node *popped;
  push(stack_head, head);
  // to avoid checking if = keep_c for each level, do top level first
  for (struct node * s = head->child; s != 0; s = s->sibling) {
    if (s != keep_c) push(stack_head, s);
  }
  while (!stack_is_empty(stack_head)) {
    popped = pop(stack_head);
    if (popped->child != 0) push(stack_head, popped->child);
    if (popped->sibling != 0) push(stack_head, popped->sibling);
    free(popped->s);
  }
  return keep_c;
}

我无法弄清楚发生了什么,因为所有节点都是用 malloc 创建的,节点指向的所有状态也是如此。

编辑:这是分配内存的代码:

void push (struct stack_node *head, struct node *k) {
  struct stack_node * x = (struct stack_node *)
    malloc(sizeof(struct stack_node));
  x->key = k;
  x->next = head->next;
  head->next = x;
  return;
}

struct stack_node * init_stack () {
  struct stack_node * head = (struct stack_node *)
    malloc(sizeof(struct stack_node));
  head->next = 0;
  return head;
}

struct node * build_game_tree (int p1, int p2) {
  struct node *head = init_game_tree();
  struct state *state = (struct state *) malloc(sizeof(struct state));
  state->player = 0;
  state->s[0] = p1; state->s[1] = p2;
  head->s = state;
  struct stack_node *stack_head = init_stack();
  struct stack_node *upper_stack_head = init_stack();
  struct node *popped;
  bool possible_moves[9];
  push(stack_head, head);
  while(!stack_is_empty(stack_head)) {
    popped = pop(stack_head);
    if (!endgame(popped->s->s[0], popped->s->s[1])) {
      push_possible_moves(stack_head, popped);
      push(upper_stack_head, popped);
    }
    else {
      popped->child = 0;
      popped->s->score =
        score(popped->s->s[0], popped->s->s[1]);
    }
  }
  ...
  return head;
}

编辑:

struct state {
  unsigned int s[2];
  double score;
  unsigned int player;
};

【问题讨论】:

  • 您需要向我们展示更多代码,至少在分配发生的位置
  • 你知道如何编写一个最小的、可编译的测试用例吗?删除任何不需要演示问题的代码。如果您的代码需要用户、套接字或文件输入,请将该逻辑替换为将字符串复制到变量中。我们的想法是给我们一个长度不到 50 行的问题的可编译演示。
  • struct state的定义在哪里? state->s 是指针,还是固定大小的数组?
  • “我无法弄清楚发生了什么”尝试打印您分配的所有内容和免费的所有内容的地址。
  • 嗨,吉姆,我已经更新了struct state 的定义。打印分配地址是个好主意,谢谢。将尝试并报告!

标签: c memory gcc malloc free


【解决方案1】:

free_children() 中,您多次尝试释放同一内存。 for 循环从第一个孩子开始,遍历所有孩子的兄弟姐妹,将它们放入堆栈。 while 循环还遍历每个孩子的兄弟姐妹,也将它们放入堆栈。每当一个节点出现在堆栈上时,您最终都会尝试free()它。

您需要重新考虑free_children() 的结构。从递归实现开始可能会更容易,如果有迫切需要,可以选择稍后将其转换为迭代实现。

【讨论】:

    猜你喜欢
    • 2011-03-17
    • 2013-11-22
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    相关资源
    最近更新 更多