Why use GLib functions?

19,152

Solution 1

In 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.

Solution 2

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.

Solution 3

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.

Solution 4

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

Solution 5

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 pointer more than once. Or sort a NULL string. But that's a mixed blessing. It prevents you from discovering these 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.

Share:
19,152
Zenet
Author by

Zenet

studying...

Updated on June 04, 2022

Comments

  • Zenet
    Zenet almost 2 years

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

  • visual_learner
    visual_learner about 14 years
    The standard free is defined to be a no-op if passed a NULL-pointer, so g_free offers no bonus there.
  • visual_learner
    visual_learner about 14 years
    The standard says that free(NULL) (or any free on a null pointer) is perfectly safe and is a no-op. No benefits there.
  • asveikau
    asveikau about 14 years
    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.
  • user2548100
    user2548100 over 10 years
    Must agree with Hans here. I'm taking over some legacy code, and it's clear to me that 4 successive crews of C programmers have been intimidated enough of all the changes that will have to be made to bring this into standard C 89 that they punted and left a huge mess. I'm just thrilled, for example, that the linked-list implementation from Gnome I'm going to have to rewrite from scratch, OR, if I can swing it, convert this code to C++ so I can use the STL. BTW, plain old vanilla C with the STL works fine, except for anonymous structures - which C++ brain-farted.
  • user2548100
    user2548100 over 10 years
    C89 all by itself is the most standard language in the World. Which would you rather debug for platform differences, C89, or C89 wrapped in some now-obscure Gnome wrapper? Yeah, me too.
  • user2548100
    user2548100 about 10 years
    My advice to anyone considering using Gnome is to use C++ for the STL. You can write "classless C++" - straight C using the STL. Works great. The amount of scope creep in the Gnome project is just ridiculous. They really think they're smarter than the people who wrote C, and they try to "fix" the language at every turn. It doesn't need fixing.
  • Admin
    Admin about 10 years
    In my experience C is more reliable than Gnome. Of course, in many cases, if you dig through Gnome code deeply enough, the Gnome function is just a #define of a standard C function. BTW, the BEST way to know how a function works on linux/Unix platforms is to use the man pages.
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams about 10 years
    "C" is not a library though, and what "libc" supports can vary from platform to platform.
  • nemequ
    nemequ about 10 years
    No, it isn't. Visual Studio doesn't support it (stackoverflow.com/questions/146381/…). Also, C99 and C89 are pretty limited—for most non-trivial projects you'll need at least some functions from POSIX/Windows API (think dlopen, threads, sockets, atomics, memory mapped files, ...), so you're going to want some sort of portability layer.
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams about 10 years
    If it makes you feel better to research the capabilities of every platform you use and lift code from other projects rather than learn about a cross-platform toolkit then I won't stop you.
  • user1717828
    user1717828 over 8 years
    @user2548100, can you provide a resource with more info on the "anonymous structure problem" in C++?
  • underscore_d
    underscore_d almost 8 years
    @user2548100 It's really reaching to say 'they think they're smarter than the people who wrote C' when in reality they just chose to use an open language in a particular way that they liked and that suited their purposes. You don't have to agree with their usage or preferences, but don't spin an absurd yarn about them being derogatory to the language or its architects. I also think C++ is totally orthogonal to this, but hey.
  • underscore_d
    underscore_d almost 8 years
    @user2548100 "plain old vanilla C with the STL" is one of the most hilariously bad contradictions in terms I've ever heard
  • Philip Withnall
    Philip Withnall over 6 years
    “Not only will you have a hard time getting your program ported some day, because you're relying on non-standard functions” is false. Part of the point of GLib is to ease porting between platforms — it provides wrapper APIs around a number of seemingly-standard functions purely because their behaviour does differ between platforms, and GLib abstracts those differences.
  • Philip Withnall
    Philip Withnall over 6 years
    The removal of GLib’s malloc vtable is more complex than just a ‘mistake’. It was removed because the need for ctor support was deemed more important than the memory profiling feature which the vtable enabled; and in the meantime, libc’s support profiling support matured significantly. See bugzilla.gnome.org/show_bug.cgi?id=751592.
  • user1703401
    user1703401 over 6 years
    Some programmers do pay attention to the license terms.
  • user877329
    user877329 over 6 years
    @PhilipWithnall What I meant was that adding it in the first place was a mistake. Removing it was not. Rather a good thing.
  • Philip Withnall
    Philip Withnall over 6 years
    At the time (although I was not around, so this is based on a bit of archaeology and what I’ve heard), I believe adding it made sense; the support for profiling memory allocations using other methods and tools was poor at the time. GLib has been around (and API stable) for a long time.
  • liberforce
    liberforce over 6 years
    @Chris Lutz: some implementations in the wild will faill on free(NULL) (I saw this myself on an embedded project). The C standard is one thing, real world necessities is another. Here's someone who saw it on another platform too: stackoverflow.com/a/1938758/518853 . That's what GLib is for: real-world portability.
  • liberforce
    liberforce over 6 years
    "Always malloc() and free() in the same scope" made me laugh. Seriously, in real world applications, you react to events, allocate memory on some, destroy that memory in response to other events. GLib documents who is responsible for freeing the memory, who takes ownership of it, and that's what you want.
  • liberforce
    liberforce over 6 years
    BTW, gboolean predates the C99 bool type. GLib started around 1996. The reasons for gboolean being gint are here: git.gnome.org/browse/glib/tree/ChangeLog.pre-1-2#n2532
  • liberforce
    liberforce over 6 years
    You show _g_vsnprintf definitions but completely dismiss the hole #ifdef HAVE_GOOD_PRINTF which show that this has been done for portability. I could debunk all the other statements, but seeing that you're too lazy to just run git blame to see why some code appeared before complaining, I won't be the one who will do your homework.
  • Admin
    Admin over 6 years
    @underscore_d, You've lead a very sheltered life!
  • Admin
    Admin over 6 years
    @PhilipWithnall, Some code will never get ported, and you are assured of that going in. Also, if you're on Linux and working on a back-end app, there aren't many other places to go, now are there? Cost and capability make that proposition very unlikely. I've ported most of my code over the last 25 yrs, and for the few advantages Gnome alleges, it's not worth the time, cost and attention span. I'd much rather take the time to revisit some of my own code, or some written by another talented programmer than use a black box written by an army of hubris.
  • underscore_d
    underscore_d over 6 years
    @RocketRoy At least you make your biases clear... as well as your lack of attention to detail, which discredits them. GNOME is a desktop. GLib is one of the libraries it uses. And you've just written off the thousands of people who ever contributed to either as "an army of hubris" and, worse, mutually exclusive with being "another talented programmer" such as, presumably, yourself. At least we know there's no point trying to have an actual discussion here (but for a slanging match, this is the place to be).
  • underscore_d
    underscore_d over 6 years
    This is just a poorly written screed, using objections most of which apply to any library above whatever you consider the acceptable baseline (C89 or POSIX). There's no sense in which "its now a legacy liability" as it remains actively developed & continually accrues modern features. Differences are documented, "legacy" features are optional & removed all the time (aside from innocuous ones like the, admittedly now silly, g typedefs), & so on. Debunking this is not a worthwhile task when simply reading some modern code using GLib would do that for you - but of course you don't want that...
  • underscore_d
    underscore_d over 6 years
    Or, more like, said native functions may simply not exist, or at least will be implemented in radically different ways that would otherwise lead to an endless nightmare of macros. Then there's all the polyfills for extremely vintage C89 (which IMO was admirable but is ever less relevant; at this point, it may be more enablement than help). Newer G* versions will start requiring C99 anyway by the looks of it - finally!
  • Philip Withnall
    Philip Withnall over 6 years
    @RocketRoy: There are valid reasons to, or to not, use GLib, depending on what aims you are trying to achieve when writing code (portability, ease of development, access to a large number of projects which use GLib, etc.). Couching your arguments in abuse and hyperbole is not helpful to anyone (me, you, or anyone trying to read this thread and get advice from it). I hope you can move on from whatever trauma you’ve had with GLib in the past and remove some of the hate from your life. I’m done here. :-)
  • Admin
    Admin over 6 years
    @PhilipWithnall, My initial reaction was to the insidious way everything calls stuff from many other modules. Then I started actually reading the code. I never saw anything creative or inspiring, but saw some really inefficient code that only existed to make use of some other piece of Gnome code. I also did enough research to find extended discussions on the tradeoffs that were made in C's string lib, and was convinced that the people who set the C Standard got it right, and the Gnome people just didn't think about the issues very much.
  • Admin
    Admin over 6 years
    Anybody who does naked free() is a noobie at best. Nobody claiming to be a professional C programmer is going to do that. NIH is a problem, but the solution isn't using someone else's black bock, it's using functions and modular code. Beyond that, GLib's version of many things, and the linked list in particular, are very abstract, but also very expensive and prone to memory leaks. Having the user allocate the memory for each link's storage, as well as the API hitting malloc() for each link might be OK if storing blobs, but if the link sizes are known a lot of complexity in the service of zilch
  • Admin
    Admin over 6 years
    @liberforce, if you're working with a compiler that's so bad free(NULL) fails you'll have much bigger problems as any such compiler would have to be hideously bad to fail in such a way and will likely produce more bugs than usable code. Find a better environment. In the meantime do what any pro would do, wrap such functions and provide useful error messages in the wrapper code.
  • Admin
    Admin over 6 years
    @underscore_d, Some poor soul at the Glib project should have read this before starting its design. The biggest problem with GLib is its hideous degree of coupling. Just off the charts. ehrscience.com/2012/11/12/…
  • Admin
    Admin over 6 years
    @liberforce. So I now have to read all kinds of documentation to use your black box, and probably dig through the code and find all the places where you do "blind" malloc()s? That's white box, not black. I write apps, not libraries and I don't make people read thousands of lines of code to find where I malloc()ed memory that they missed and thus failed to free(). I make it obvious. If you aren't you're writing bad code.
  • liberforce
    liberforce over 6 years
    It fails at runtime, not at compile time, so not the compiler fault. The "find a better environment" is laughable when you're on big projects with fixed delivery dates. About your "the one that do what I do are noobs" argument, that's at best, childish.
  • liberforce
    liberforce over 6 years
    @RocketRoy You make it obvious, right. And that's what GLib does. The ownership of the memory is documented, and that is what is used to generate the bindings for GLib, GTK+... You don't need to "guess".
  • liberforce
    liberforce over 6 years
    @RocketRoy About GLib maintainers that started it in 1996 that should have read, before designing it, an article from 2012... I suppose they forgot their crystal ball to read in the future.
  • six-k
    six-k about 6 years
    ...one absolute maxium of C coding: "Always malloc() and free() in the same scope... I'm not sure which 'scope' you had in mind and neither do I know of any source which claims this as "one absolute maxium of C coding" nor the meaning of "maxium". Nevertheless, +1 for looking behind the curtain.
  • six-k
    six-k about 6 years
    @RocketRoy "Imagine what they could have achieved if they hadn't wasted their time on GLib." They probably might have wasted time using some other library written by another "army of hubris". Even the most accomplished developers may not have self-written libraries for all data structures they will ever need. Say, for an application prototype, we may not want to spend time implementing a full blown hash table. I'm not a fan of glib but it does save me numerous hours(and headache) while prototyping. And for that, I do appreciate and thank the community that develops glib.
  • smac89
    smac89 almost 3 years
    Your explanation for g_strcmp0 is slightly off. It is true that the function handles NULL strings, but it does not treat them the same as empty strings. In other words, g_strcmp0 (NULL, "") will not return 0, but -1