我有以下使用 strdup 函数的代码
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
char source[] = "The Source String ";
int main()
{
char *dest;
if ((dest = _strdup(source)) == NULL)
{
fprintf(stderr, " Error allocation memory. ");
exit(1);
}
printf("The destination = %s\n", dest);
return 0;
}
它成功地说出了 The Source String,但我很感兴趣它在哪种情况下会失败,以及它在日常问题中的使用效果如何?我知道它是由 strdup 决定的
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
}
如果我们的字符串不为 NULL,是否有可能导致 strdup 函数失败?
最佳答案
是的,如果 malloc
分配内存失败并返回 NULL
。
当您尝试复制一个非常大的字符串时,或者如果您的地址空间非常零散且几乎已满(因此 malloc
无法找到连续的内存块),这可能会合理地发生分配,或在没有太多内存可用的嵌入式系统中。
关于c - 当 strdup 功能失败时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9927747/