X Toolkit:重建小部件时堆正在增长

时间:2017-07-21 14:22:14

标签: c memory-leaks widget xlib motif

我试图理解为什么以下程序泄漏内存。当我使用命令more /proc/<pid>/smaps查看堆大小时,我可以看到堆只在增长。似乎XtDestroyWidget并没有真正释放内存。如果有人能告诉我为什么会发生这种情况并向我展示重新创建小部件的正确方法,我将非常感激。 提前谢谢!

/* Compile on Solaris: cc widgets_mem.c -lXm -lXt -lX11 */
/* Compile on Linux: gcc -m32 widgets_mem.c -lXm -lXt -lX11 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

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

#include <Xm/MainW.h>
#include <Xm/PushB.h>
#include <Xm/Form.h>


Widget      toplevel;
Widget      w_main;
Widget      w_bb;
Widget      w_button = NULL;

Window      root_win;
XtAppContext    app;
int     screen_number;
Display        *display = NULL;

void recreateWidgets ()
{
    printf ("recreating widgets\n");
    XtDestroyWidget (w_button);

    w_button = XtVaCreateManagedWidget (
    "button",
    xmPushButtonWidgetClass, w_bb,
    XmNfillOnArm, False,
    XmNhighlightThickness, 0,
    XmNborderWidth, 1,
    XmNmarginTop, 1,
    XmNmarginWidth, 2,
    XmNmarginHeight, 0,
    XmNwidth, 20,
    XmNheight, 10,
    XmNrecomputeSize, False,
    XmNalignment, XmALIGNMENT_CENTER,
    NULL);
}


void main (int argc, char **argv)
{
    XEvent  event;

    toplevel = XtVaAppInitialize (&app, "Mem leak test",
                  NULL, 0, &argc, argv, NULL, NULL);
    display = XtDisplay (toplevel);
    screen_number = DefaultScreen (display);
    root_win = RootWindow (display, screen_number);

    w_main = XtVaCreatePopupShell (
    "main", 
    topLevelShellWidgetClass, toplevel,
    XmNgeometry, "-0+0",
    XmNborderWidth, 0,
    XmNshadowThickness, 0,
    XmNminWidth, 1, 
    XmNmwmDecorations, 0,
    XmNmwmFunctions, 0,
    XmNwidth, 600,
    XmNheight, 200,
    NULL);

    w_bb = XtVaCreateManagedWidget (
    "",
    xmBulletinBoardWidgetClass, w_main,
    XmNborderWidth, 4,
    XmNshadowThickness, 0,
    XmNmarginWidth, 0,
    XmNmarginHeight, 0,
    XmNx, 0,
    XmNy, 0,
    XmNwidth, 500,
    XmNheight, 100,
    NULL);

    w_button = XtVaCreateManagedWidget (
    "button",
    xmPushButtonWidgetClass, w_bb,
    XmNfillOnArm, False,
    XmNhighlightThickness, 0,
    XmNborderWidth, 1,
    XmNmarginTop, 1,
    XmNmarginWidth, 2,
    XmNmarginHeight, 0,
    XmNwidth, 20,
    XmNheight, 10,
    XmNrecomputeSize, False,
    XmNalignment, XmALIGNMENT_CENTER,
    NULL);

    XtPopup (w_main, XtGrabNone);

    while (1)
    {
        XtAppNextEvent (app, &event);
        if (event.type == ButtonPress)
        {
            printf ("Button pressed, recreating widgets\n");
            recreateWidgets();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我在代码中发现了错误:我必须添加一个XtDispatchEvent(&amp; event),它处理目标列表中的小部件的解除分配,Xt中的内部列表。