malloc
提供: cppreference.com
<tbody>
</tbody>
| ヘッダ <stdlib.h> で定義
|
||
void* malloc( size_t size ); |
||
size バイトの未初期化記憶域を確保します。
確保が成功した場合は、基本アライメントを持つあらゆるオブジェクト型に対して適切にアラインされたポインタを返します。
size がゼロの場合、 malloc の動作は処理系定義です。 例えば、ヌルポインタが返されるかもしれません。 そうでなく、非ヌルなポインタが返されるかもしれません (そのようなポインタは逆参照するべきではありません。 また、メモリリークを回避するためには free に渡す必要があります)。
|
メモリ領域を解放する free または realloc の以前の呼び出しは、同じメモリ領域またはその一部を確保する |
(C11以上) |
引数
| size | - | 確保するバイト数 |
戻り値
成功した場合は、新たに確保されたメモリの先頭を指すポインタを返します。 メモリリークを回避するためには、返されたポインタは free() または realloc() で解放しなければなりません。
失敗した場合は、ヌルポインタを返します。
例
Run this code
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p1 = malloc(4*sizeof(int)); // allocates enough for an array of 4 int
int *p2 = malloc(sizeof(int[4])); // same, naming the type directly
int *p3 = malloc(4*sizeof *p3); // same, without repeating the type name
if(p1) {
for(int n=0; n<4; ++n) // populate the array
p1[n] = n*n;
for(int n=0; n<4; ++n) // print it back out
printf("p1[%d] == %d\n", n, p1[n]);
}
free(p1);
free(p2);
free(p3);
}
出力:
p1[0] == 0
p1[1] == 1
p1[2] == 4
p1[3] == 9
参考文献
- C11 standard (ISO/IEC 9899:2011):
- 7.22.3.4 The malloc function (p: 349)
- C99 standard (ISO/IEC 9899:1999):
- 7.20.3.3 The malloc function (p: 314)
- C89/C90 standard (ISO/IEC 9899:1990):
- 4.10.3.3 The malloc function
関連項目
malloc の C++リファレンス
|