hi friends,
what is the diff. between strcpy() and strdup(). Both duplicate string right?
Printable View
hi friends,
what is the diff. between strcpy() and strdup(). Both duplicate string right?
No they don't
strcpy is a standard function which copies a \0 terminated array of chars from one place to another (so long as they don't overlap)
strdup is a non-standard function which MAY allocate some memory and copy a string into that memory.
Hmmm. Salem, can you give an example of when strdup DOESN'T return a new memeory location? I did some looking (honestly not long) on Google and couldn't come up with anything.
I am guessing this is what Salem meant...
strdup returns a pointer to the new duplicate string, or NULL if there was not enough memory. In general, strdup makes a call to malloc to allocate space for the new string - if malloc can't get enough space, neither can strdup, so in this case no duplicate string. Since strdup requests space from malloc it may or may not allocate some memory and copy the string into the new space, depending on what malloc returns.
More specifically, an ANSI-C implementation isn't required to implement strdup() AT ALL.
Even if you have two systems providing strdup(), you have to read the manual for both to make sure it's what you want.
That's why it's a non-standard function.
So, if then the lib that one is using has strdup, does it ALWAYS allocate memory, or are there any that would keep a static buffer such that one would need to do his/her own malloc and then strcpy?
Granted, there is no requirement for strdup in C, however, I don't know of a lib that doesn't offer it. But, that wasn't my point. I was only wondering if there was some other, to use the term loosely, non-standard way of implementing strdup?
The reason that I even asked is because you said it "MAY allocate" memmory. . . which made me think that you already knew of some other way strdup was implemented.
You mean like using two standard functions - malloc and strcpy to implement it yourself and be sure that the result will be portable?