Search code examples
c++opencvxlib

How do I deallocate the memory create in this function?


I've done a lot of searching on google, and I'm still not sure about this.

cv::Mat ImageFromDisplay(int Width, int Height, int x, int y)
{
    Display* display = XOpenDisplay(NULL);
    Window root = DefaultRootWindow(display);
    XWindowAttributes attributes = {0};
    XGetWindowAttributes(display, root, &attributes);
    XImage* img = XGetImage(display, root, x, y, Width, Height, AllPlanes, ZPixmap);
    if (!img->data) {
        cout << "No image data";
        throw("No image data");
    }
    cv::Mat scene = cv::Mat(Height, Width, img->bits_per_pixel > 24 ? CV_8UC4 : CV_8UC3, img->data);
    if (!scene.data) {
        cout << "Error reading scene";
        throw("Error reading scene");
    }
    cvtColor(scene, scene, CV_BGRA2BGR);
    XFree(img);
    XCloseDisplay(display);
    return scene;
}

Whenever I use this function, I later use cv::Mat->release on the object that is returned, like so:

cv::Mat sceneImg = ImageFromDisplay(SCENE_WIDTH, SCENE_HEIGHT);
sceneImg.release();

Will all the memory allocated by this function be cleaned up once sceneImg goes out of scope?

I know that I call free on the img within ImageFromDisplay, and I call XCloseDisplay on display from ImageFromDisplay, so I'm assuming the memory for those data structures gets cleaned up. Do I need to delete sceneImg.data after sceneImg.release has been called?


Solution

  • Found a comment in the same place where I found the original code, pointing out the memory leak. Totally fixed my program.

    ... I wanted to say that the answer provided by Brandon leaks memory. Use XDestroyImage(img); instead of XFree(img); in the function ImageFromDisplay