strdup() function

Usually, you just use an #if to define the function you want when under a certain compiler. If the built-in library doesn’t define strdup, there is no problem in defining it yourself (other than if they do define it in the future, you’ll have to take it out.) // Only define strdup for platforms that … Read more

strdup or _strdup?

Which is correct? strdup is a perfectly correct POSIX function. Nevertheless, it doesn’t belong to the standard, and the ANSI C standard reserves some (broad) classes of function names for further use. Among these, there are Function names that begin with str and a lowercase letter therefore, the MS guys decided to replace strdup with … Read more

strcpy vs strdup

strcpy(ptr2, ptr1) is equivalent to while(*ptr2++ = *ptr1++) where as strdup is equivalent to ptr2 = malloc(strlen(ptr1)+1); strcpy(ptr2,ptr1); (memcpy version might be more efficient) So if you want the string which you have copied to be used in another function (as it is created in heap section) you can use strdup, else strcpy is enough.

strdup() – what does it do in C?

Exactly what it sounds like, assuming you’re used to the abbreviated way in which C and UNIX assigns words, it duplicates strings 🙂 Keeping in mind it’s actually not part of the ISO C standard itself(a) (it’s a POSIX thing), it’s effectively doing the same as the following code: char *strdup(const char *src) { char … Read more