繁体   English   中英

喜欢的列表内存释放问题/内存泄漏

[英]Liked list memory freeing issue/memory leak

我在一个函数中有内存泄漏,我不明白它为什么会发生,也不知道如何修复它。 函数的目的是根据 key1 的值重新排列链表,它工作得很好,但由于某种原因它有内存泄漏/我没有正确释放它

void ascending1 (Node * node, int A){
    int i = 0;
    double Temp_Key1[A];
    int Temp_Val[A];
    double Temp_Key2[A];
   double temp2 = 0;
    double temp3 = 0;
    int temp1 = 0;
    int amount = 0;
    int x = 0;

    for ( i = 0; i < A; i++ ){
        Temp_Key1[i] = 0;
        Temp_Key2[i] = 0;
        Temp_Val[i] = 0;
    }

    Node *sort1_head;
    sort1_head = NULL;
    for (i = 0; i<A ; i++ ){
        Temp_Key1[i] = node->key1;
        Temp_Key2[i] = node->key2;
        Temp_Val[i] = node->value;
        node = node->next;
    }

    amount = A-1;
    while (x<=amount){
     for (i = 0; i<A ; i++ ){

         if (Temp_Key1[i] < Temp_Key1[i+1]){
             temp2 = Temp_Key1[i];
             Temp_Key1[i] = Temp_Key1[i+1];
             Temp_Key1[i+1] = temp2;

             temp3 = Temp_Key2[i];
             Temp_Key2[i] = Temp_Key2[i+1];
             Temp_Key2[i+1] = temp3;

             temp1 = Temp_Val[i];
            Temp_Val[i] = Temp_Val[i+1];
            Temp_Val[i+1] = temp1;
         }
    }
        x++;
    }

    for ( i = A ; i >= 0 ; i--){
      node = malloc(sizeof(Node));
      node->value = Temp_Val[i];
      node->key1 =  Temp_Key1[i];
      node->key2 =  Temp_Key2[i];
      node->sort1 = sort1_head;  
      sort1_head = node;
      }

    printf("\n");
    printf("Following the sort1 links:\n");
    print_list1(node);
    sort1_head = NULL;
    free_list(node);
}

释放它的函数是

 void free_list(Node * head){
    Node * new_head = head;
    Node * old_node = NULL;

    while (new_head != NULL){
        old_node = new_head;
        new_head = new_head->next;
        free(old_node);
    }

}

Valgrind 给了我以下错误:

==20167== Conditional jump or move depends on uninitialised value(s)
==20167==    at 0x10928C: free_list (FuncDef.c:19)
==20167==    by 0x109B24: ascending1 (FuncDef.c:199)
==20167==    by 0x10922D: main (main.c:26)
==20167==  Uninitialised value was created by a heap allocation
==20167==    at 0x483577F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==20167==    by 0x109A75: ascending1 (FuncDef.c:181)
==20167==    by 0x10922D: main (main.c:26)
==20167== 
==20167== 
==20167== HEAP SUMMARY:
==20167==     in use at exit: 48 bytes in 1 blocks
==20167==   total heap usage: 6 allocs, 5 frees, 2,240 bytes allocated

你的循环是错误的:

for (i = 0; i<A ; i++ ){
   if (Temp_Key1[i] < Temp_Key1[i+1]){

但是对于iA-1 ,没有Temp_Key1[i+1] ,即没有Temp_Key1[A ]。

你的循环也一样

for ( i = A ; i >= 0 ; i--){
    node->value = Temp_Val[i];

没有Temp_Val[A]

只需更改为

for (i = 0; i<A-1 ; i++ ){

for ( i = A-1; i >= 0 ; i--){

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM