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
?
Reading some documentation for
strdup
, I don't notice any obvious differences, apart from thatg_strdup
specifies that you can pass itNULL
whereasstrdup
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:
g_strdup()
will abort the program on a memory allocation failure, as per GLib’s general allocation policy. This is because it’s basically impossible to test all the error handling paths in anything other than a small program if you try and handle allocation failures; and allocation failures are very rare on systems with virtual memory and no pre-existing program bugs (such as allocation size calculation bugs).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.