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!
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!
Their behavior is well-defined on any platform that GTK+ supports, as opposed to the native functions which may perhaps sometimes partway work.
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.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.
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.