Re: [gtk-list] Re: Found: Shortest way to trigger core-dump :-(



Andreas Tille wrote:

> On Wed, 21 Apr 1999 Bertrand.Guiheneuf@inria.fr wrote:
>
> > static void Function(void *data, GtkSignalFunc func, char *question)
> > {
> >   GtkWidget *window, *button;
> >
> >   window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
> >   gtk_signal_connect(GTK_OBJECT(window), "destroy", GTK_SIGNAL_FUNC(gtk_widget_destroyed), &window);
> >
> > &window is a pointer to somerthing in the stack....
> >
> > put GtkWidget *window, *button; outside you r  function, this
> > will resolve youe segmentation fault.
> Why shouldn't I use internal variables in this case?
> I really didn't see any reason and I want to avoid global variables
> because I consider it to be bad style.
>
> OK, it would solve the Problem, but declaring the variables static would
> solve the problem, too.
>
> But could you explain, why for instance this
>

Well, stack corruption often leads to funny bugs....

using a pointer to an object in the stack as a *global*
callback data is an error. It may work if the stack has not been
not overwritten when the the window object is accessed
(for instance if you don't call functions
between the moment you allocate the variable in the
stack, and the moment the callback is called).


>
> static void MainCallback(GtkWidget *button, char *dummy)
> {
>   char    *file, *buf;
>
>   file = g_strdup("");
>   /*  buf  = g_strdup(""); */
>   Function(file, GTK_SIGNAL_FUNC(Callback), NULL);
>   /*  if ( buf )  g_free(buf);  */
> }
>
> solves the problem as well???  What has this really unneeded pointer
> to do with *window and *button??
>

In this case, compiler optimisation may be responsible:

Local variables in a function are allocated in the stack, after
function parameters:

---- SP  ----
function param 1
function param2
local variable1
local variable2  (this may be where window was stored)
------------

as you can see in this figure, window may have been stored
at the same place as "local variable 2"

If you don't use one of the local variables in your function, the
compiler simply does not put it it in the stack (and thus does not
initialize it to 0). This is why "window" is stil alive :)

hope this helps

Bertrand

PS: I think you have no choice but putting you window
object in "global" space, ie use malloc or declare
it statically as a (may be static) variable.





[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]