tags:

views:

292

answers:

4

Hello,

While programming in C and GTK+, Why is it "better" to use g_strdup_printf, g_free, g_strcmp0 etc... and fellow glib functions?

Merci!

+3  A: 

Their behavior is well-defined on any platform that GTK+ supports, as opposed to the native functions which may perhaps sometimes partway work.

Ignacio Vazquez-Abrams
+4  A: 

I general, GLib's purpose is a utility and portability library. Those in itself are reasons to consider using it.

The specific functions you mention all offer something extra on top of their C standard library variants:

  • g_strdup_printf is like sprintf, but actually allocates the buffer for you and saves you the guesswork of how large the buffer should be. (The return value should be g_free'd.)
  • g_free is like free, but checks for a NULL-pointer.
  • g_strcmp0 is like strcmp, but treats a NULL-pointer like an empty string, and thus sorts it in front.
Shtééf
The standard `free` is defined to be a no-op if passed a `NULL`-pointer, so `g_free` offers no bonus there.
Chris Lutz
Still a good idea to match `g_malloc()` with `g_free()` instead of `free()` from libc. I have observed that on Windows it's possible for multiple DLLs to link to separate versions of `malloc()` (with separate internal heap structures) and mixing-and-matching causes crashes. Not sure if this is a real world concern or if it might be true on other platforms, but by using GLIB's wrappers you can avoid that.
asveikau
Glib also has hooks in `g_malloc()` and `g_free()` where you can add debugging functions to check for memory leaks: http://library.gnome.org/devel/glib/stable/glib-Memory-Allocation.html#glib-mem-profiler-table
ptomato
Oh yeah, and `g_malloc()` will terminate the program if it fails to allocate the memory, as opposed to `malloc()` where you have to check that the returned pointer is not `NULL`...
ptomato
+2  A: 

For consistent behavior in multiple operating systems. It's a portability thing.

In some other unix environments other than Linux, or if your program is compiled on windows, some of those functions may not exist or behave differently on the target operating system.

Using the glib versions ensure consistent behavior.

Bob
+1  A: 

I have to say, this is well intended but not well executed. It is sorta nice that your program won't crash and burn when you try to free() a NULL pointer. Or sort a NULL string. But that's a mixed blessing. It prevents you from discovering nasty bugs in your code as well. Not only will you have a hard time getting your program ported some day, because you're relying on non-standard functions, you'll have a really hard time because your code was buggy and you never found out.

Hans Passant
The standard says that `free(NULL)` (or any free on a null pointer) is perfectly safe and is a no-op. No benefits there.
Chris Lutz