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 new string is: this is a copy

関連情報