strdup() — ストリングの複製

フォーマット

#include <string.h>
char *strdup(const char *string);
注: strdup 関数は、C++ プログラムで使用可能です。 __cplusplus__strings__ マクロがプログラムで定義されている場合にのみ、C でも使用できます。

言語レベル

XPG4、Extension

スレッド・セーフ

はい

説明

strdup は、malloc を呼び出して、string のコピー用の予約ストレージ・スペースを予約します。 この関数のストリング引数には、ストリングの終わりを示すマークであるヌル文字 (\0) が含まれると想定されます。 strdup を呼び出して予約したストレージは、忘れずに解放してください。

戻り値

strdup は、コピーされたストリングを含むストレージ・スペースを指すポインターを戻します。 ストレージ strdup を予約できない場合は、NULL を戻します。

この例では、strdup を使用して、ストリングを複製し、コピーを出力します。
#include <stdio.h>
#include <string.h>
int main(void)
{
   char *string = "this is a copy";
   char *newstr;
   /* Make newstr point to a duplicate of string                              */
   if ((newstr = strdup(string)) != NULL)
      printf("The new string is: %s\n", newstr);
   return 0;
}
The output should be:
      The new string is: this is a copy