strdup() - what does it do in C?

前端 未结 10 2274
情话喂你
情话喂你 2020-11-21 23:22

What is the purpose of the strdup() function in C?

相关标签:
10条回答
  • 2020-11-22 00:26

    The most valuable thing it does is give you another string identical to the first, without requiring you to allocate memory (location and size) yourself. But, as noted, you still need to free it (but which doesn't require a quantity calculation, either.)

    0 讨论(0)
  • 2020-11-22 00:28
    char * strdup(const char * s)
    {
      size_t len = 1+strlen(s);
      char *p = malloc(len);
    
      return p ? memcpy(p, s, len) : NULL;
    }
    

    Maybe the code is a bit faster than with strcpy() as the \0 char doesn't need to be searched again (It already was with strlen()).

    0 讨论(0)
  • 2020-11-22 00:28

    strdup and strndup are defined in POSIX compliant systems as:

    char *strdup(const char *str);
    char *strndup(const char *str, size_t len);
    

    The strdup() function allocates sufficient memory for a copy of the string str, does the copy, and returns a pointer to it.

    The pointer may subsequently be used as an argument to the function free.

    If insufficient memory is available, NULL is returned and errno is set to ENOMEM.

    The strndup() function copies at most len characters from the string str always null terminating the copied string.

    0 讨论(0)
  • 2020-11-22 00:29

    From strdup man:

    The strdup() function shall return a pointer to a new string, which is a duplicate of the string pointed to by s1. The returned pointer can be passed to free(). A null pointer is returned if the new string cannot be created.

    0 讨论(0)
提交回复
热议问题