C中的内存泄漏 - 故障排除

时间:2017-03-25 08:35:19

标签: c memory-leaks

我有一个复杂的程序,我把问题缩小到了这个范围。我不能为我的生活找到泄漏的地方。我试图打印出"%p"对于使用malloc构建的每个指针,并将其与使用free()释放的所有指针进行比较。

我已经接受了下面的代码。我正在使用valgrind找到泄漏。它显示:     堆概要:         在退出时使用:189个块中的66.419个字节       总堆使用量:365个分配,176个释放,79个767个字节分配

LEAK SUMMARY:
    definitely lost: 26 372 bytes in 121 blocks
    indirectly lost: 66 bytes in 5 blocks
      possibly lost: 0 bytes in 0 blocks
    still reachable: 39 981 bytes in 63 blocks
         suppressed: 0 bytes in 0 blocks

这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

struct IntItem {
    int value;
    struct IntItem *next;
    struct IntItem *prev;
};
typedef struct IntItem IntItem;


void freeList(struct IntItem *current_node)
{
// Loops through the array to free all nodes
    while(current_node -> next != NULL){
        current_node = current_node -> next;
        free(current_node -> prev);
    }
    free(current_node);
}


struct IntItem *createList(char input[500]) {
    struct IntItem *item, *tempPtr;

    //Allocate memory for the first node
    tempPtr = (struct IntItem*) malloc(sizeof(IntItem));

    //Sets the pointers so I can move up and down in the array
    tempPtr -> next= NULL;
    tempPtr -> prev= NULL;
    tempPtr -> value = (input[0] - '0');


    //Loops through the string to form an array of IntItem
    item = tempPtr;
    for(int i = 1; i < strlen(input); ++i){

        item -> next= (struct IntItem*) malloc(sizeof(struct IntItem));

        // Sets an head on the next element
        item -> next-> prev= item;

        // Jumps to the next node
        item = item->next;

        // Assign a value to the node
        item -> value = (input[i] - '0');

        item -> next= NULL;
    }
    return tempPtr;
}

int main(){
    //Initiate data
    char baseText[500];
    struct IntItem *base;

    //Get data input
    printf("Input your base Number:\n");
    scanf("%s",baseText);

    //Convert it to a list
    base = createList(baseText);

    //Free the list
    freeList(base);

    return 0;
}

0 个答案:

没有答案