#include <gtk/gtk.h>

GtkMenu* pMenu = 0;
GtkMenuItem* pMenuItem = 0;
GtkAccelLabel* pLabel = 0;

void on_menu_item_activate(GtkMenuItem* object, gpointer data)
{
  GObject* pObject = G_OBJECT(pMenuItem);
  g_warning("before remove: refcount=%d", pObject->ref_count);

  gtk_container_remove(GTK_CONTAINER(pMenu), GTK_WIDGET(pMenuItem));

  GObject* pObject2 = G_OBJECT(pMenuItem);
  g_warning("after remove: refcount=%d", pObject2->ref_count);

  gtk_accel_label_set_accel_widget(pLabel, 0);

  GObject* pObject3 = G_OBJECT(pMenuItem);
  g_warning("after unsetting label's accel widget: refcount=%d", pObject3->ref_count);

}

void on_menu_item_destroyed(GtkMenuItem* object, gpointer data)
{
  //This callback will never be called if
  //gtk_accel_label_set_accel_widget() is used below:
  g_warning("on_menu_item_destroyed");
}

int main(int argc, char* argv[])
{
    gtk_init(&argc, &argv);

    GtkWindow* pWindow = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL);
    GtkVBox* pBox = (GtkVBox*)gtk_vbox_new(FALSE, 0);
    gtk_container_add(GTK_CONTAINER(pWindow), GTK_WIDGET(pBox));

    GtkMenuBar* pMenuBar = (GtkMenuBar*)gtk_menu_bar_new();
    gtk_container_add(GTK_CONTAINER(pBox), GTK_WIDGET(pMenuBar));
    gtk_widget_show(GTK_WIDGET(pMenuBar));

    GtkMenuItem* pMenuItemRoot = (GtkMenuItem*)gtk_menu_item_new_with_label("Root");
    gtk_menu_shell_insert(GTK_MENU_SHELL(pMenuBar), GTK_WIDGET(pMenuItemRoot), 0);
    gtk_widget_show(GTK_WIDGET(pMenuItemRoot));

    pMenu = (GtkMenu*)gtk_menu_new();
    gtk_menu_item_set_submenu(GTK_MENU_ITEM (pMenuItemRoot), GTK_WIDGET(pMenu));

    pMenuItem = (GtkMenuItem*)gtk_menu_item_new(); //_with_label("_test");
    //We could use gtk_menu_item_new_with_label() to show the problem, but this is
    //what happens inside, so let's isolate the problem:
    {
        pLabel = (GtkAccelLabel*)gtk_accel_label_new("_text");
        gtk_container_add(GTK_CONTAINER(pMenuItem), GTK_WIDGET(pLabel));
        gtk_widget_show(GTK_WIDGET(pLabel));

        //This adds the reference that will be leaked:
        gtk_accel_label_set_accel_widget(GTK_ACCEL_LABEL(pLabel), GTK_WIDGET(pMenuItem));
    }
   
    gtk_menu_shell_insert(GTK_MENU_SHELL(pMenu), GTK_WIDGET(pMenuItem), 0); 
    gtk_widget_show(GTK_WIDGET(pMenuItem));


    g_signal_connect_swapped(G_OBJECT(pMenuItem), "activate",
		                      G_CALLBACK (on_menu_item_activate), 
                                      0);
    g_signal_connect(G_OBJECT(pMenuItem), "destroy", G_CALLBACK(on_menu_item_destroyed), 0);

    
    gtk_widget_show_all(GTK_WIDGET(pWindow));
    
    g_warning("before gtk_main(): refcount=%d", G_OBJECT(pMenuItem)->ref_count);
    gtk_main();
    
    return 0;
}
