0

我已经 6 年多没用过 C 或 C++ 了,有点生疏了。我正在为图形遍历算法编写一些快速测试代码。该代码接受邻接列表样式输入。但是我遇到了free/的一些问题malloc

我的代码有两个问题:

  1. 当我在没有free和没有代码的情况下运行代码getchar时,当我使用 VC++ cntrl-f5 时,代码会挂起。这在我使用getchar(). 有谁知道为什么?

  2. 当我免费运行代码时,代码挂起。我试图调试代码,它完全挂在free语句上。关于如何解决这个问题的任何建议?

另外,如果我对这段代码做任何危险的事情,请告诉我。头文件被省略。

  void * s_malloc(size_t size){
    void * ret_pntr = malloc(sizeof(size));
    if (ret_pntr == NULL){
        printf ("error");
        exit(1);
    }
    return (void *)malloc(sizeof(size));
  }

  void initialize_graph(graph * G1, int num_vertices){
    int i = 0 ;
    G1->num_vertices = num_vertices;
    G1->node_list = (node**)s_malloc(sizeof(node*)*num_vertices);
    for (i = 0; i < num_vertices; i ++){
        G1->node_list[i] = (node *)s_malloc(sizeof(node));
    }
  }

  void free_everything(graph * G1){
    int i = 0;
    node * ref = NULL;
    for (i = 0; i < G1->num_vertices; i++){
        ref = G1->node_list[i];
        recursive_remove(ref);
    }
    free(G1->node_list);
  }

  void recursive_remove(node * ref){
    if (ref == NULL){
        return;
    }
    else{
        recursive_remove(ref->next);
    }
    free(ref);
  }

  int main(){
    int i = 0;
    graph * G1 = (graph*)s_malloc(sizeof(graph));
    G1->init = &initialize_graph;
    G1->init(G1, 10);
    G1->remove = &free_everything;
    G1->node_list[0]->value = 1;
    G1->node_list[0]->next = (node*)s_malloc(sizeof(node));
    G1->node_list[0]->next->value = 2;
    G1->node_list[0]->next->next = NULL;
    G1->node_list[1]->value = 10;
    printf("%d\n", G1->node_list[0]->next->value);
    printf("%d\n", G1->node_list[1]->value);
    G1->remove(G1);
    free(G1);
    getchar();
   }
4

1 回答 1

4

立即跳出来的一件事是

void * s_malloc(size_t size){
  void * ret_pntr = malloc(sizeof(size));
  if (ret_pntr == NULL){
    printf ("error");
    exit(1);
  }
  return (void *)malloc(sizeof(size));
}

您分配了两次,泄漏了第一次分配,并且没有检查第二次分配的结果。另一个是你的malloc电话应该是

 malloc(size)

不是

 malloc(sizeof(size))

因为在您当前的代码中,您的所有内存分配不足(每次分配一次只会给您 4 个字节),您的访问会全部结束......我很惊讶执行实际上使它成为getchar()or free()

尚不清楚为什么您在使用 VC++ 时尝试在 C 中模拟 OOP。如果您使用 STL 容器在 C++ 中重写它来保存您的节点并使用索引而不是指针,我认为您的很多问题都会消失。但是现在为你调试这个烂摊子对任何人来说都不好玩。

更好的解决方案是使用现有的图形库,例如Boost Graph

于 2012-04-06T05:31:03.383 回答