2013-07-13 34 views
7

从阅读有关的“可能丢失” Valgrind的内存泄漏报告,我的理解是,有一个很小的机会,这样的报告会出现假阳性的报告。我无法理解在正常情况下如何发生这种情况,而无需执行非常强迫代码的操作。是否有一个假阳性valgrind“可能丢失”报告的简单例子?

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

回答

1

这里是“可能失去”假阳性的例子:

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()); 
} 

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

+0

有也“可能失去”的报告的情况下,一个很好的例子,因为我不知道如何有可能是在这种情况下,假阳性的报告? – user2579277

+0

@ user2579277:对不起,我无法响应更快,我现在已经添加了一个更直接的例子。 – cmaster

+0

很抱歉,您可能丢失的新示例在valgrind报告中未显示为问题。对于第二个例子,asprint在内核中分配内存,所以valgrind报告不是误报。 – user2579277