【发布时间】:2018-05-12 15:23:44
【问题描述】:
我正在尝试使用 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(在 /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 个)
我计划每秒读取数百个像素,所以我需要摆脱这个内存泄漏。 有谁知道这样做的正确方法吗?
谢谢
【问题讨论】:
标签: c++ c memory-leaks valgrind x11