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

时间:2022-01-08 08:59:37

I am trying to get a pixel from the screen using the X11/Xutil library, but, according to valgrind, there seems to be a memory leak in the code:

我试图使用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 output

==27380== HEAP SUMMARY:
==27380== in use at exit: 96 bytes in 1 blocks
==27380== total heap usage: 66 allocs, 65 frees, 141,257 bytes allocated
==27380==
==27380== Searching for pointers to 1 not-freed blocks
==27380== Checked 141,304 bytes
==27380==
==27380== 96 bytes in 1 blocks are definitely lost in loss record 1 of 1
==27380== at 0x4C2CE5F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27380== by 0x4E60BD6: XGetImage (in /usr/lib/libX11.so.6.3.0)
==27380== by 0x108BB8: main (in /home/cafeina/source codes/MachineLearning/dinosaur/cpp/get_pixel)
==27380==
==27380== LEAK SUMMARY:
==27380== definitely lost: 96 bytes in 1 blocks
==27380== indirectly lost: 0 bytes in 0 blocks
==27380== possibly lost: 0 bytes in 0 blocks
==27380== still reachable: 0 bytes in 0 blocks
==27380== suppressed: 0 bytes in 0 blocks
==27380==
==27380== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

== 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 == LEAK SUMMARY:== 27380 ==绝对丢失:1个块中的96个字节== 27380 ==间接丢失:0个块中的0个字节== 27380 ==可能丢失:0个块中的0个字节== 27380 ==仍然可达:0个块中的0个字节== 27380 ==抑制:0个块中的0个字节== 27380 = = == 27380 ==错误摘要:1个上下文中的1个错误(抑制:0从0开始)

I am planning on reading hundreds of pixels, many times per second, so I need to get rid of this memory leak. Does anyone know the proper way to do this?

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

Thank you

1 个解决方案

#1


3  

Use XDestroyImage(image) instead of XFree(image)

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

#1


3  

Use XDestroyImage(image) instead of XFree(image)

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