简体   繁体   English

如何修复 C 中的这些 memory 泄漏?

[英]How do I fix these memory leaks in C?

I am working on a function which allocates memory into an array, and then I free it later.我正在研究一个 function ,它将 memory 分配到一个数组中,然后我稍后释放它。 Oddly enough, valgrind is giving me this error:奇怪的是,valgrind 给了我这个错误:

==93== HEAP SUMMARY:
==93==     in use at exit: 11,160 bytes in 2,232 blocks
==93==   total heap usage: 44,310 allocs, 42,078 frees, 1,632,230 bytes allocated
==93==
==93== 11,160 bytes in 2,232 blocks are definitely lost in loss record 1 of 1
==93==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==93==    by 0x10976F: FillHashMap (in /mnt/c/Users/Jordan/Documents/GitHub/flwg/flwp)
==93==    by 0x1092F1: main (in /mnt/c/Users/Jordan/Documents/GitHub/flwg/flwp)
==93==
==93== LEAK SUMMARY:
==93==    definitely lost: 11,160 bytes in 2,232 blocks
==93==    indirectly lost: 0 bytes in 0 blocks
==93==      possibly lost: 0 bytes in 0 blocks
==93==    still reachable: 0 bytes in 0 blocks
==93==         suppressed: 0 bytes in 0 blocks
==93==
==93== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

Dr. Memory is giving me a similar error: Memory 博士给了我一个类似的错误:

Error #1: UNADDRESSABLE ACCESS: reading 0x0000000000000000-0x0000000000000008 8 byte(s)
# 0 testing               [C:/Users/Jordan/Documents/GitHub/flwg/FLWP-2.c:120]
# 1 main                  [C:/Users/Jordan/Documents/GitHub/flwg/FLWP-2.c:105]
Note: @0:00:01.195 in thread 14704
Note: instruction: mov    (%rax) -> %rax

The strcmp line of code is what causes it to break with Dr. Memory, although valgrind says I have issues even if I don't call this particular method. strcmp 代码行是导致它与 Dr. Memory 中断的原因,尽管 valgrind 说我有问题,即使我不调用这个特定方法。

void testing(struct wordConnections *header){
    header = header->nextRow;
    
    while(strcmp(header->word, "berk") != 0){ 
        header = header->nextRow; 
        if(header == NULL){
         printf("Failed");
         return; 
        }
    }
}

The code that runs is (the value and significance of numLetters + 1 is it is the length of the char* stored in the wordStorage, the value of numLetters is 4):运行的代码是(numLetters + 1的值和意义是wordStorage中存储的char*的长度,numLetters的值是4):

char** FillHashMap(struct wordConnections **(*HashMap)){
    int h = 0; 
    /* The Amount of words in each file, File 1, 2, 3 */
    int totalWordQuantity[3] = {132, 7420, 19829}; 
    /*the word that we test, we add by two because first 4: word, 5th: \n, 6th: \0*/
    char word[numLetters + 1]; 
    /*how many times we've changed the character*/
    int letterSpot = 0; 
    /*the character that goes through the file*/
    char c; 
    FILE *flwd = OpenFile(); 
    /* is it the first word of the line */
    int wordCount = 0; 
    int isFirst = 1; 
    char p = fgetc(flwd); 
    c = p; 
    /* So, this is a temporary word, who will store the row, so all of its category folks will be contained within it */
    char* rowWord = malloc(sizeof(char) * (numLetters + 1)); 
    /*This stores all of the words*/
    char** wordStorage = (char**)calloc(totalWordQuantity[numLetters - 2], sizeof(char*) * (numLetters + 1));
    int i = 0; 
    /* First, take the character */
    while((c = p) != EOF){
        
        p = fgetc(flwd);

        /* Add the character to the word */
        word[letterSpot] = c; 
        /* Allows the letter spot to find the next place into the word */
        letterSpot++; 
        
        /* Determines if the character is the placement immediately after the word */
        if((c == ' ' && p != '\n') || c == '\n'){
            
            letterSpot = 0; 
            /* Throws in the \0, converting into a string */
            word[numLetters] = '\0'; 
            
            wordStorage[wordCount] = malloc(sizeof(char) * (numLetters + 1));
            h++;
            strcpy(wordStorage[wordCount], word); 
                
            /* Determine if it's the first word */
            if(isFirst == 1){
                strcpy(rowWord, word); 
                 
                /* Throw it in as a row */
                AddRow2DLL(wordStorage[wordCount], 
                         HashMap[FirstHashFunction(word[0])/*First Letter*/]
                                [SecondHashFunction(word)]/*First Vowel*/);     
            }
            /* If it's not the first word */
            else {
                AddColumn2DLL(wordStorage[wordCount], 
                       HashMap[FirstHashFunction(rowWord[0])/*First Letter*/]
                              [SecondHashFunction(rowWord)]/*First Vowel*/); 
            }
            
            if(c == ' '){
                isFirst = 0; 
            }
            if(c == '\n'){
                isFirst = 1; 
            }
            wordCount++; 
        }
        c = p; 
    }
    free(rowWord);
    fclose(flwd); 
    return wordStorage; 
}

The hash map works fine, this is the method that causes the issues, without it, there are no memory leaks. hash map 工作正常,这是导致问题的方法,没有它,没有 memory 泄漏。

Later in the code, I free the wordStorage array with this method:稍后在代码中,我使用以下方法释放 wordStorage 数组:

void FreeWordStorage(char** wordStorage){
    int f = 0;  
    /* The Amount of words in each file, File 1, 2, 3 */
    int totalWordQuantity[3] = {132, 7420, 19829}; 
    int i; 
    for(i = 0; i < totalWordQuantity[numLetters - 2]; i++){
        free(wordStorage[i]); 
        f++; 
    }
     
    free(wordStorage);
}

I've tried all sorts of things to fix it.我已经尝试了各种方法来修复它。 Oddly enough, when I check it with integers, I'm allocating and freeing the same amount of data.奇怪的是,当我用整数检查它时,我分配和释放了相同数量的数据。

Any help would be greatly appreciated.任何帮助将不胜感激。 Thank you!谢谢!

Valgrind's analysis indicates that the leaked memory was allocated by a bunch of malloc() calls by function FillHashMap() , and the only plausible candidate for those is this: Valgrind 的分析表明,泄露的 memory 是由 function FillHashMap()的一堆malloc()调用分配的,唯一可能的候选者是:

 wordStorage[wordCount] = malloc(sizeof(char) * (numLetters + 1));

Function FreeWordStorage() appears to be correct for freeing the data allocated by FillHashMap() , so if some allocations are going unfreed then there are two main possibilities: Function FreeWordStorage()似乎对于释放由FillHashMap()分配的数据是正确的,因此如果某些分配将被释放,那么主要有两种可能性:

  1. The pointer value returned by FillHashMap() is not later passed to FreeWordStorage() . FillHashMap()返回的指针值稍后不会传递给FreeWordStorage() The latter function might not be called at all on the code path that is being exercised, or perhaps a modified or outright wrong pointer is being passed to it.后一个 function 可能根本不会在正在执行的代码路径上调用,或者可能是一个修改过的或完全错误的指针被传递给它。 Or,或者,

  2. Some or all of the pointers recorded in the allocated block returned by FillHashMap() are modified after being recorded, so that when it is called, FreeWordStorage() is ineffective at freeing the allocated memory. FillHashMap()返回的已分配块中记录的部分或全部指针在记录后被修改,因此调用时FreeWordStorage()在释放已分配的memory时无效。

Either one of those could be consistent with Dr. Memory's diagnostic, but whichever scenario applies, it does not appear to play out in the code presented in the question.其中任何一个都可能与 Dr. Memory 的诊断一致,但无论哪种情况适用,它似乎都不会在问题中提供的代码中发挥作用。 I am reasonably confident that your pointers are being mangled somewhere else in the program.我有理由相信您的指针在程序的其他地方被破坏了。

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

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