Cライブラリ関数 -malloc()
説明
Cライブラリ関数void *malloc(size_t size)必要なメモリ領域を割り当て、それを指すポインタを返します。
宣言
以下は malloc() 関数の宣言です。
void *malloc(size_t size)
引数
- size-- メモリブロックのサイズ(バイト単位)。
戻り値
この関数は、割り当てられたサイズのメモリを指すポインタを返します。要求が失敗した場合は、NULL を返します。
例
以下の例は、malloc() 関数の使用方法を示しています。
例
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *str;
/*最初のメモリ割り当て*/
str = (char *) malloc(15);
strcpy(str, "サンプル");
printf("String = %s, Address = %u\n", str, str);
/*メモリの再割り当て*/
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
}
上記のプログラムをコンパイルして実行すると、次の結果が得られます。
String = サンプル, Address = 3662685808 String = example.com, Address = 3662685808その他の拡張
C標準ライブラリ - <stdlib.h>