Most of the open source applications using GTK I've come across cast g_free as GWeakNotify. Whereas g_free's signature allows for a single argument: g_free(), the GWeakNotify typedef allows for two: GWeakNotify.
I wrote a simple program to check the cast and it looks OK - that is, the second parameter is 'let through':
#include <stdlib.h>
#include <stdio.h>
#include <gtk/gtk.h>
void
callFree(GWeakNotify notify, gpointer pData, GObject *pObject)
{
notify(pData, pObject);
}
int
main(int argc, char **argv)
{
(void)argc;
(void)argv;
gpointer pData = g_malloc(32);
GObject *pNull = (GObject *)g_malloc(64); //results in a 64B leak
if (!pData)
{
fprintf(stdout, "Unable to allocate pdata\n");
}
else
{
fprintf(stdout, "pData allocated OK...freeing\n");
callFree((GWeakNotify)g_free, pData, pNull);
}
return EXIT_SUCCESS;
}
My questions are: 1) What's going on behind the scenes? Is the second argument simply left on the stack and g_free doesn't care about it (since it's not supposed to)?
2) Why does the compiler not complain about it given the two signatures (1 parameter for g_free and two for GWeakNotify)?
Thanks! P
That's the way the C calling convention works; the calling code pushes the arguments onto the stack and cleans them up again. The called function doesn't care how many arguments there are, it only uses the ones it needs. This is how variable-argument functions such as printf()
can work.
The compiler doesn't complain about it precisely because of the GWeakNotify
cast; basically you're telling it "Don't complain that these functions have different signatures." If you left out the cast, it would complain.
(Note that pData
will never be NULL
in your code; g_malloc()
aborts the program if it can't allocate the requested memory. If you want the other behavior, use g_try_malloc()
or regular malloc()
.)