Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strdup dumping core on passing NULL

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.

like image 200
hari Avatar asked Jun 21 '11 21:06

hari


2 Answers

That's quite ok.

The documentation implies that it's argument must be string, if it's something else, such as a null pointer, it's anyones 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 behavor if you pass them something you're not supposed to. Many standard C function such as strcpy, strlen does not accept null pointers either.

like image 90
nos Avatar answered Oct 08 '22 02:10

nos


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.

like image 30
Ben Voigt Avatar answered Oct 08 '22 02:10

Ben Voigt