cglibstrdup

Is there any reason to use g_strdup from GLib over strdup from the C standard library?


I've been working on an application written in C that uses GLib and exclusively targets Linux. Generally my experience has been that GLib's utilities are useful and generally make writing C easier compared to just using the C standard library. Then I noticed that g_strdup exists. Reading some documentation for strdup, I don't notice any obvious differences, apart from that g_strdup specifies that you can pass it NULL whereas strdup doesn't mention how it behaves in this scenario.

Given this information, is there any reason for me to use g_strdup over strdup?


Solution

  • Reading some documentation for strdup, I don't notice any obvious differences, apart from that g_strdup specifies that you can pass it NULL whereas strdup doesn't mention how it behaves in this scenario.

    Their behaviour when NULL is passed as an input is one difference. The other key difference is:

    Other than that, the two only exist because g_strdup() predates the standardised form of strdup() by a couple of decades.

    Their implementations (g_strdup(), strdup()) are basically identical, modulo the differences in handling NULL input and allocation failure — they both measure the input string length, allocate space for it, then call memcpy() to copy the bytes to the new allocation. That’s unlikely to change.

    One minor optimisation which g_strdup() has is that it optimises out the strlen() call for known-constant strings. So it will be immeasurably faster for some strings. There’s no reason the libc strdup() couldn’t do this in future too though.

    Personally I’d choose g_strdup() to avoid having to explicitly deal with NULL input strings separately, or handle allocation failure, but the usefulness of that to you depends on your program’s policy about whether strings can be NULL in general, and how your program handles allocation failures.