是否有一个假阳性valgrind"可能丢失"报告的简单例子?

use*_*277 7 c++ valgrind memory-leaks

通过阅读关于"可能丢失"的valgrind内存泄漏报告,我了解到这种报告很可能是一个误报的报告.我无法理解如何在正常情况下发生这种情况而不做一些非常强迫代码的事情.

因此,为了理解这个选项,我问的是有一个假阳性valgrind"可能丢失"内存泄漏报告的简单例子吗?

cma*_*ter 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.
}
Run Code Online (Sandbox Code Playgroud)

这是一个更一般的误报示例:

//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());
}
Run Code Online (Sandbox Code Playgroud)

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