的strdup() - 这是什么在C呢? [英] strdup() - what does it do in C?

查看:144
本文介绍了的strdup() - 这是什么在C呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是的strdup的目的(c)中功能?

推荐答案

这听起来像(假设你已经习惯了在C和UNIX分配字的简写方式)究竟是什么,它​​重复字符串。

Exactly what it sounds like (assuming you're used to the abbreviated way in which C and UNIX assigns words), it duplicates strings.

在牢记它实际上不是ISO C标准本身(这是一个POSIX的东西),它有效地做同样为以下code的一部分:

Keeping in mind it's actually not part of the ISO C standard itself (it's a POSIX thing), 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
}

在换句话说:


  1. 它试图分配足够的内存来保存旧的字符串(加一个空字符标记字符串的结束)。

  2. 如果分配失败,它集错误号 ENOMEM 并返回 NULL 立即(错误号设置为 ENOMEM 的东西的malloc 这样做,我们并不需要明确地做它在我们的的strdup )。

  3. 否则,分配工作,所以我们老的字符串复制到新的字符串,返回新的地址(主叫方负责在某一点释放)。

  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 to ENOMEM 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 at some point).

请记住这是概念性的定义。正在使用的任何图书馆的作家值得他们的薪水可能提供高度优化的code针对特定的处理器。

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

如果您在功能痛恨多个出口(我不知道,除非它影响可读性,我不认为是这样的短暂功能的情况下)的人群的一部分,你可以写code作为:

If you're part of the crowd that abhors multiple exit points in functions (I don't unless it affects readability, which I don't believe to be the case for such a short function), you can write the code as:

char *strdup (const char *s) {
    char *d = malloc (strlen (s) + 1);   // Allocate memory
    if (d != NULL) strcpy (d,s);         // Copy string if okay
    return d;                            // Return new memory
}

这篇关于的strdup() - 这是什么在C呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆