strdup() Copy string

本文深入解析了C语言中用于复制字符串的内置函数strdup的实现细节,包括内存分配、字符串复制及错误处理机制。通过理解其工作原理,读者能够更好地掌握字符串操作的基础知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值