使用 "X11/Xutil.h" 库读取像素时的内存泄漏(使用 valgrind 输出)
Memory leak when using "X11/Xutil.h" library to read pixels (with valgrind output)
我正在尝试使用 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== 堆摘要:
==27380== 在退出时使用:1 个块中的 96 个字节
==27380== 总堆使用量:66 次分配,65 次释放,141,257 字节分配
==27380==
==27380== 正在搜索指向 1 个未释放块的指针
==27380== 已检查 141,304 字节
==27380==
==27380== 1个块中的96个字节肯定丢失在丢失记录1 of 1中
==27380== 在 0x4C2CE5F:malloc(在 /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so 中)
==27380== 通过 0x4E60BD6:XGetImage(在 /usr/lib/libX11.so.6.3.0 中)
==27380== by 0x108BB8: main (in /home/cafeina/source codes/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)
我计划读取数百个像素,每秒多次,因此我需要消除这种内存泄漏。
有谁知道这样做的正确方法吗?
谢谢
使用 XDestroyImage(image) 而不是 XFree(image)
我正在尝试使用 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== 堆摘要:
==27380== 在退出时使用:1 个块中的 96 个字节
==27380== 总堆使用量:66 次分配,65 次释放,141,257 字节分配
==27380==
==27380== 正在搜索指向 1 个未释放块的指针
==27380== 已检查 141,304 字节
==27380==
==27380== 1个块中的96个字节肯定丢失在丢失记录1 of 1中
==27380== 在 0x4C2CE5F:malloc(在 /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so 中)
==27380== 通过 0x4E60BD6:XGetImage(在 /usr/lib/libX11.so.6.3.0 中)
==27380== by 0x108BB8: main (in /home/cafeina/source codes/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)
我计划读取数百个像素,每秒多次,因此我需要消除这种内存泄漏。 有谁知道这样做的正确方法吗?
谢谢
使用 XDestroyImage(image) 而不是 XFree(image)