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:
#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;
}
==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)
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
Use XDestroyImage(image) instead of XFree(image)