i would like to know if strdup adds a '\0' at the end of the new array if the src array does not contain one ?
let's assume we have an array containing "hello" allocated by this kind of malloc
malloc(sizeof(char) * 5);
so 5 bytes for 5 characters.
I guess the src string did not received the sufficient memory for the '\0'.
What is supposed to happen in this case ?
First the standard disclaimer: strdup
isn't a standardized function, so exactly what it does could (at least in theory) vary from one compiler to the next. That said, every implementation I've seen of it has worked the same way.
strdup
will determine the length of the input string--it'll start from the address in the pointer you pass, and find the first NUL byte after that location. Then it'll allocate a new block of memory and copy the bytes in that range to the newly allocated block.
So one of two things will happen. Either the input will contain a zero byte, and the result will too, or else strdup
will read past the end of the input you passed, and you'll get undefined behavior (but chances are pretty good it'll find a zero byte eventually, and copy a bunch of extra garbage to the duplicate string).
One other minor note: if you use strdup
, and then try to port you code to a compiler that doesn't define it, you might consider writing your own:
char *strdup(char const *s) {
size_t len = strlen(s) + 1;
char *ret = malloc(len);
if (ret != NULL)
strcpy(ret, s);
return ret;
}
That's obviously a pretty easy thing to do, but it has one other problem: including it in your code produces undefined behavior. You're not allowed to write a function with a name that starts with str
. Those are all reserved for the implementation. So even though the function is simple and the behavior of its content is perfectly well defined, the mere existence of the function as a whole still gives undefined behavior.