SYNOPSIS
       #include 

       char *strdup(const char *s);
DESCRIPTION
This convenient little str function will malloc space, and copy into said space, the passed string s, returning a pointer to said space.

NOTES
Sure, it's not glamorous or ritzy, but it's useful. Meat and potatoes, if you will.

This is a case of code re-use. The code to copy a string into a new buffer is pretty basic. But it's just complex enough that writing it out a dozen times is a pain, and prone to errors or typo's.

strdup is a convenience function: Given a string, it mallocs sufficient memory for copying the string, then strcpys it into the new block. It's a quick way to create a dynamically-allocated copy of an existing string.

Unfortunately, strdup is nonstandard. So ISO C (and ANSI C) implementations needn't support it. None of the C library string functions involves dynamic memory allocation (malloc() and friends).

Of course, you could try to define it in your program:

char *strdup(const char *s)
{
  char *r = malloc(strlen(s)+1);
  if (r)
    strcpy(r, s);
  return r;
}

Except you're not allowed to. All lowercase external identifiers beginning "str..." are part of the implementation namespace, and a portable C program may not use them!

This odd rule really makes sense here. After all, many (most?) implementations do supply strdup(), and code like the above would break due to multiple definition of the function...

Log in or register to write something here or to contact authors.