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;
}
ソース文字列は正常に表示されますが、どの状況で失敗するのか、また日常の問題でどのように使用されているのか興味深いのですが、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 関数が失敗する可能性はありますか?