Reputation: 9733
strdup(null) dumps core.
Tried in on ubuntu and freeBSD both.
why? Shouldn't it return null?
char *b = NULL;
a = strdup(b);
This will dump core on strdup call.
Upvotes: 14
Views: 16115
Reputation: 229184
That's quite ok.
The documentation implies that its argument must be a string. If it's something else, such as a null pointer, it's anyone's guess what'll happen. In essence, you get undefined behavior when passing a NULL
pointer to strdup
.
It's quite normal for functions to yield undefined behavior if you pass them something you're not supposed to. Many standard C functions such as strcpy
and strlen
do not accept null pointers either.
Upvotes: 26
Reputation: 283733
strdup
returns NULL in case of allocation failure.
This is not allocation failure. The behavior when a wild pointer is passed in is undefined. You're required to pass in a valid pointer to a NUL-terminated string.
Upvotes: 8
Reputation: 2984
Of course, all the answers are correct. Nonetheless, in case of strdup(), it would be nice to have it to be able to deal with null pointers, too - just return a "null" string too, in that case. Of course, it is easy to define a strdupnullok() function with that behaviour as a wrapper around strdup(), but it is then an additional wrapper and function call, so makes code a tiny bit slower.
Upvotes: 2