C-standard-library-c-function-malloc

提供:Dev Guides
移動先:案内検索

Cライブラリ関数-malloc()

説明

Cライブラリ関数 void malloc(size_t size)*は、要求されたメモリを割り当て、それへのポインタを返します。

宣言

以下は、malloc()関数の宣言です。

void *malloc(size_t size)

パラメーター

  • サイズ-これはバイト単位のメモリブロックのサイズです。

戻り値

この関数は、割り当てられたメモリへのポインタを返します。リクエストが失敗した場合はNULLを返します。

次の例は、malloc()関数の使用法を示しています。

#include <stdio.h>
#include <stdlib.h>

int main () {
   char *str;

  /*Initial memory allocation*/
   str = (char *) malloc(15);
   strcpy(str, "finddevguides");
   printf("String = %s,  Address = %u\n", str, str);

  /*Reallocating memory*/
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);

   return(0);
}

次の結果を生成する上記のプログラムをコンパイルして実行しましょう-

String = finddevguides, Address = 355090448
String = finddevguides.com, Address = 355090448