strdup() Copy string

来源:互联网 发布:it服务项目经理证书 编辑:程序博客网 时间:2024/05/14 17:20

It's effectively doing the same as the following code:

char *strdup (const char *s) {    char *d = malloc (strlen (s) + 1);   // Space for length plus nul    if (d == NULL) return NULL;          // No memory    strcpy (d,s);                        // Copy the characters    return d;                            // Return the new string}

In other words:

  1. It tries to allocate enough memory to hold the old string (plus a null character to mark the end of the string).
  2. If the allocation failed, it sets errno to ENOMEM and returns NULL immediately (setting of errno toENOMEM is something malloc does so we don't need to explicitly do it in our strdup).
  3. Otherwise the allocation worked so we copy the old string to the new string and return the new address (which the caller is responsible for freeing).

Keep in mind that's the conceptual definition. Any library writer worth their salary should have provided heavily optimised code targeting the particular processor being used.

原创粉丝点击