使用“X11 / Xutil.h”库读取像素时使用内存泄漏(使用valgrind输出)

时间:2017-11-29 02:14:27

标签: c++ c memory-leaks valgrind x11

我试图使用X11 / Xutil库从屏幕上获取一个像素,但是根据valgrind的说法,代码中似乎存在内存泄漏:

get_pixel.cpp

#include <iostream>
#include <X11/Xutil.h>

int main(int argc, char** argv)
{
    Display *display = XOpenDisplay(nullptr);

    int x = 10;
    int y = 10;
    XImage *image;
    image = XGetImage(display, RootWindow(display, DefaultScreen(display)),
        x, y, 1, 1, AllPlanes, XYPixmap);

    XColor color;
    color.pixel = XGetPixel(image, 0, 0);
    XFree(image);
    XQueryColor(display, DefaultColormap(display, DefaultScreen (display)), &color);
    std::cout << color.red/256 << " " << color.green/256 << " " << color.blue/256 << "\n";

    XCloseDisplay(display);
    return 0;
}

Valgrind输出

== 27380 == HEAP SUMMARY:
== 27380 ==在退出时使用:1个块中的96个字节
== 27380 ==总堆使用量:66个分配,65个释放,141,257个字节分配
== 27380 ==
== 27380 ==搜索指向1个未释放块的指针
== 27380 ==检查141,304字节
== 27380 ==
== 27380 == 1个块中的96个字节肯定会丢失在1的丢失记录1中 == 27380 ==在0x4C2CE5F:malloc(在/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
== 27380 == by 0x4E60BD6:XGetImage(在/usr/lib/libX11.so.6.3.0中)
== 27380 == by 0x108BB8:main(在/ home / cafeina /源代码/ MachineLearning / dinosaur / cpp / get_pixel)
== 27380 ==
== 27380 ==泄漏摘要:
== 27380 == 绝对丢失:1个区块中的96个字节
== 27380 ==间接丢失:0块中的0字节
== 27380 ==可能丢失:0块中的0字节
== 27380 ==仍然可以访问:0个块中的0个字节
== 27380 ==抑制:0块中的0字节
== 27380 ==
== 27380 ==错误摘要:1个上下文中的1个错误(被抑制:0从0开始)

我计划每秒读取数百个像素,所以我需要摆脱这种内存泄漏。 有谁知道这样做的正确方法?

谢谢

1 个答案:

答案 0 :(得分:3)

使用XDestroyImage(图像)代替XFree(图像)