0

I'm a beginner with xlib. I tried to program an Xwindow application using select() based on this example: how to quit the blocking of xlib's XNextEvent.

But the code mentioned above crashes in the XPending function. So I tried to isolate the problem and on my system even this from my point of view very simple example crashes on line 28. Due to several tests I assume is crashes internally by calling XFlush(). At the line marked with "// <- CRASH" I think XPending should return 0. Is that correct?

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

Display *dis;
Window win;
int x11_fd;
fd_set in_fds;

struct timeval tv;
XKeyEvent ev;

int main() {
    dis = XOpenDisplay(NULL);
    win = XCreateSimpleWindow(dis, RootWindow(dis, 0), 1, 1, 256, 256, \
        0, BlackPixel (dis, 0), BlackPixel(dis, 0));

    XSelectInput(dis, win, 
        KeyPressMask | KeyReleaseMask );

    XMapWindow(dis, win);
    XFlush(dis);
    printf("Xpending: %d\n",XPending(dis));  
    printf("Xpending: %d\n",XPending(dis));  
    XPeekEvent(dis, (XEvent*) &ev);
    printf("type: %d button: 0x%X state: 0x%x\n",ev.type, ev.keycode, ev.state);  
    int j = XPending(dis); // <- CRASH
    printf("XPending: %d\n",j);  
    return 0;
}

Is this a bug or have I mistaken a major concept in xlib?

Community
  • 1
  • 1

2 Answers2

1

XKeyEvent is bigger in bytes than XEvent when you receive a bigger event, the ev variable will overflow. using malloc, you actualy get more bytes than you asked, solving the problem. better solution will be using a XEvent ev;

XEvent ev;
...
XNextEvent( & ev );
...
printf( "%d\n", ev.xkey.keycode

);

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
nacho
  • 11
  • 1
0

I have solved the issue. Although I don't understand why it works:

Instead of using a global ev variable I declared it inside the main function body:

XKeyEvent *ev = (XKeyEvent*) malloc(sizeof(XKeyEvent));

and adapted its pointer nature to the program.