strdup() - what does it do in C?

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

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

10条回答
  •  耶瑟儿~
    2020-11-22 00:17

    strdup() does dynamic memory allocation for the character array including the end character '\0' and returns the address of the heap memory:

    char *strdup (const char *s)
    {
        char *p = malloc (strlen (s) + 1);   // allocate memory
        if (p != NULL)
            strcpy (p,s);                    // copy string
        return p;                            // return the memory
    }
    

    So, what it does is give us another string identical to the string given by its argument, without requiring us to allocate memory. But we still need to free it, later.

提交回复
热议问题