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:
- It tries to allocate enough memory to hold the old string (plus a null character to mark the end of the string).
-
If the allocation failed, it sets
errnotoENOMEMand returnsNULLimmediately (setting oferrnotoENOMEMis somethingmallocdoes so we don't need to explicitly do it in ourstrdup). - 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.
本文深入解析了C语言中用于复制字符串的内置函数strdup的实现细节,包括内存分配、字符串复制及错误处理机制。通过理解其工作原理,读者能够更好地掌握字符串操作的基础知识。
3万+

被折叠的 条评论
为什么被折叠?



