While programming in C and GTK+, why is it \"better\" to use g_strdup_printf
, g_free
, g_strcmp0
etc... and fellow GLib functions?
The GLib provides portability and basic stuff you'd expect nowadays from any programming language, like collection types (linked lists, arrays, hash tables, etc.). Here are some of the benefits GLib can give you.
Portability
The point of the GLib is to be portable not to the C standard, but to the implementations of the standard. The GLib takes care of the known quirks that might seem useless at first sight until you need to port your code to a platform that has those nasty bugs.
Let's take the example of g_free
, as many criticize it. There are platforms where free(NULL) will fail, even if C99 says it should work. That check exists since at least 1998 (I tracked it in git history). Some may say it's not needed anymore, but even in 2017 I worked at a company that checks for NULL
before calling free
because otherwise it would crash on their embedded platform. It also serves as a wrapper for intrumentation of your code when you want to do some serious memory debugging.
Readability
It helps improving the readability of your code by providing some wrapper functions that not only improve portabitlity, but also help you avoid many language pitfalls. How many of you test malloc
to see if it returns NULL
? How many of you have a way to recover if it returns NULL
, since you're basicly out of memory?
g_malloc
will abort the application if it can't allocate what you want, and in many applications, this is just the behavior you want. For very big allocations that may fail, you have g_try_malloc
. That is the same as malloc but still gives you the benefit of being a wrapper that may be used for instrumentation.
Being able to write:
char *buffer = g_malloc(30);
/* Do something with it ... */
g_free (buffer);
...frees the mind and lets the developer focus on the task she's trying to achieve. It also avoids having your program crash much later because it's trying to write using NULL
pointer and you have to track down the allocation.
The standard C library is full of traps, and not having to micro manage every single line of code you write is a relief. Just read the BUGS section of the manpages for some functions and youo'll see. Having less boilerplate code to check for errors makes the code simpler to read, which improves the maintainability, and causes less bugs.
Features
Another point is the whole bunch of collection types GLib provides and that you don't have to reimplement. Just because reimplementing a linked list is easy doesn't mean you should do it. I worked at another company that shipped code with several linked list implementations, because some developpers would just have the Not Invented Here syndrome and would redevelop their own. A common, thouroughly tested, widespread library like GLib helps avoiding this nonsense. You shouldn't redevelop that stuff unless you have very specific performance constraints.