7

通过阅读“可能丢失”的valgrind内存泄漏报告,我了解到这种报告是误报的可能性很小。如果不对代码做一些非常强制的事情,我无法理解在正常情况下如何发生这种情况。

所以为了理解这个选项,我问是否有一个简单的假阳性 valgrind“可能丢失”内存泄漏报告的例子?

4

1 回答 1

0

以下是“可能丢失”的误报示例:

class A {
    int x;
};
class B {
    int y;
};
class C : public A, B {
    int z;
};

int main() {
    static B* notLost = new C();    //The upcast will change the pointer to point 4 bytes into the object, because that is the offset of the B subobject within the C object.
    //Valgrind thinks, the new object may be possibly unreachable.
    //But I can still do this:
//  delete (C*)notLost; //The downcast undoes the pointer modification by the upcast.
}

这是一个更通用的误报示例:

//get asprintf
#define _GNU_SOURCE
#include <stdio.h>
#include <assert.h>

char* getFoo() {
    static char* foo = NULL;
    if(!foo && asprintf(&foo, "Hello World\n") < 0) assert(0);
    return foo;
}

int main() {
    printf("%s", getFoo());
}

这是一个典型的单例理念:在某个地方有一个函数,它提供对一个特殊对象(这里是“Hello World”字符串)的访问,确保只创建一个这样的对象。由于对象永远不会被破坏/释放,Valgrind 不得不认为它是内存泄漏。通常这些被列为“仍然可以访问”,因为仍然存在可以访问它的静态变量,但它仍然是误报。

于 2013-07-13T15:25:06.520 回答