XQueryTree上的分段错误

时间:2016-07-08 20:52:44

标签: c++ window x11 xlib

我试图关闭最后使用的窗口(堆叠顺序中当前窗口下方的窗口)。不幸的是XQueryTree由于某种原因发生了段错误。

#pragma once

#include <X11/Xlib.h>
#include <X11/Xutil.h>

namespace WindowingOperations {

    inline void closeLastWindow() {
        Display* dpy = XOpenDisplay(0);
        Window root = DefaultRootWindow(dpy);

        Window* root_return;
        Window* parent_return;
        Window** children_return;
        unsigned int* nchildren_return;

        XQueryTree(dpy,
                   root,
                   root_return,
                   parent_return,
                   children_return,
                   nchildren_return);

        // Kill the window right after this one
        if (*nchildren_return > 1)
            XDestroyWindow(dpy, *children_return[*nchildren_return - 2]);
    }
}

编辑:

如果您需要测试用例:

#include "window_operations.h"
int main() {
    WindowingOperations::closeLastWindow();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

_return参数需要去的地方。您无法传入未初始化的指针,需要为XQueryTree分配存储空间以便将结果写入。

因此...

namespace WindowingOperations {

    inline void closeLastWindow() {
        Display* dpy = XOpenDisplay(0);
        Window root = DefaultRootWindow(dpy);

    // Allocate storage for the results of XQueryTree. 
        Window root_return;
        Window parent_return;
        Window* children_return;
        unsigned int nchildren_return;

    // then make the call providing the addresses of the out parameters
        if (XQueryTree(dpy,
                       root,
                       &root_return,
                       &parent_return,
                       &children_return,
                       &nchildren_return) != 0)
        { // added if to test for a failed call. results are unchanged if call failed, 
          // so don't use them

            // Kill the window right after this one
            if (*nchildren_return > 1)
                XDestroyWindow(dpy, *children_return[*nchildren_return - 2]);
        }
        else
        {
            // handle error
        }
    }
}