繁体   English   中英

如何检查 C 中的 memory 泄漏?

[英]how can i check for memory leaks in C?

这是我第一次使用动态 memory 分配,我不知道如何在我的代码中检查 memory 泄漏

总的来说,我如何在 Visual Studio 中检查 memory 泄漏? 我不知道如何跟踪堆和堆栈,所以我主要是在黑暗中拍摄。

我应该提到我使用了 windows 10 并且据我所知 Valgrind 不提供对 W10 的支持

Dictionary* createDic(Dictionary* dics, int* size) {
    Dictionary* temp = NULL;
    //some extra code for the variables below which arent al that important for the question
    temp = malloc(++*size * sizeof(Dictionary));
    if (temp==NULL)
    {
        printf("\nThe creation of the dictionary has failed!");
        *size+=-1;
        freeArray(splitReciever,count);
        return dics;
    }
    for (int i = 0; i < (*size - 1); i++)
    {
        temp[i] = dics[i];
    }
    temp[*size - 1].languages = splitReciever;
    temp[*size - 1].numOfLanguages = count;
    temp[*size - 1].wordList = NULL;
    dics = temp;
    return dics;
}

我还想知道这段代码是否会再次起作用,而不会导致 memory 泄漏?

Dictionary* createDic(Dictionary* dics, int* size) {
    Dictionary* temp = NULL;
    //some extra code for the variables below which arent al that important for the question
    temp = realloc(dics , ++*size * sizeof(Dictionary));
    if (temp==NULL)
    {
        printf("\nThe creation of the dictionary has failed!");
        *size+=-1;
        freeArray(splitReciever,count);
        return dics;
    }
    temp[*size - 1].languages = splitReciever;
    temp[*size - 1].numOfLanguages = count;
    temp[*size - 1].wordList = NULL;
    dics = temp;
    return dics;
}

To check for memory leaks tools like valgrind can be used – while these cannot give you guarantees of (in-)existence of memory leaks or for finding any location of a memory leak – there are false positives and negatives possible – their results still provide pretty关于你应该在哪里再次检查你的代码的有价值的提示。

监控 memory 的消耗也可以给你进一步的提示; 如果它超出合理限制,那么您可能有 memory 泄漏。

对于您的具体示例:

第一个变体可能会产生 memory 泄漏,但不一定

Dictionary d1 = ...;
Dictionary d2 = createDic(d1, &n);

// now you could use both of d1 and d2
// however risk of double deletion if re-allocation failed;
// need to compare d1 and d2 for equality before freeing them

Dictionary d3 = ...;    // assume this is the sole pointer to d3
d3 = createDic(d3, &n); // if re-allocation succeeded last reference to
                        // old dictionary is lost -> memory leak

第二种变体避免了这种情况,但有另一个缺点:

Dictionary d1 = ...;
Dictionary d2 = createDic(d1, &n);

如果成功,指针d1会失效,读取它会导致未定义的行为。 因此,您还必须将其更新为新值。

总之,第二个变体应该会带来更少的麻烦,所以我更喜欢它。 顺便说一句:如果您修改该变体以在成功返回之前删除旧字典,则相当于第一个变体......

暂无
暂无

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

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