File tree Expand file tree Collapse file tree 1 file changed +79
-0
lines changed Expand file tree Collapse file tree 1 file changed +79
-0
lines changed Original file line number Diff line number Diff line change 1+ # realloc
2+ * cstdlib[ meta header]
3+ * std[ meta namespace]
4+ * function[ meta id-type]
5+
6+ ``` cpp
7+ namespace std {
8+ void* realloc(void* ptr, size_t new_size);
9+ }
10+ ```
11+
12+ ## 概要
13+ 確保済みの領域`ptr`を`new_size`に再確保する。
14+
15+ `ptr`は、`calloc`、`malloc`、`realloc`で事前に確保され、なおかつ`free`で解放されていないメモリである必要がある。
16+
17+ それ以外のメモリの場合、動作は未定義である。
18+
19+ `ptr`に`nullptr`を渡した場合、`malloc(new_size)`として動作する。
20+
21+ ## 効果
22+ メモリの確保は次のいずれかの方法で行われる。
23+
24+ - 既存のメモリを拡張、縮小する。
25+
26+ 縮小した場合、再確保されたメモリのサイズまでの領域の内容が保持される。
27+
28+ 拡張した場合、新しい領域の内容は未定義である。
29+
30+ - 新しいサイズの領域を確保、割り当てする。その後、新しいサイズと古いサイズのいずれか小さい方のサイズに等しいメモリ領域をコピーし、古いブロックを解放する。
31+
32+ - メモリが不足している場合、`nullpte`が返される。
33+
34+ ## 備考
35+ `new_size`が0の場合の動作は定義されていない。
36+
37+ ## 戻り値
38+ 再確保できた場合、その領域の先頭のポインタを返す。
39+
40+ なお、その領域はメモリリークを避けるため、`free`、`realloc`で解放する必要がある。
41+
42+ 失敗した場合、`nullptr`を返す。もとのポインタは有効なままで、解放する必要がある。
43+
44+ ## 例
45+ ```cpp example
46+ #include <cstdlib>
47+ #include <iostream>
48+
49+ int main() {
50+ // 初期サイズでメモリを確保
51+ int* p = static_cast<int*>(std::malloc(5 * sizeof(int)));
52+ if (!p) return 1;
53+ for (int i = 0; i < 5; ++i) {
54+ p[i] = i;
55+ }
56+ // サイズを再確保(拡張)
57+ int* q = static_cast<int*>(std::realloc(p, 10 * sizeof(int)));
58+ if (!q) {
59+ std::free(p);
60+ std::cerr << "realloc failed" << std::endl;
61+ return 1;
62+ }// 拡張後の内容を出力(追加領域の値は未定義)
63+ for (int i = 0; i < 10; ++i) {
64+ std::cout << q[i] << ' ';
65+ }
66+ std::cout << std::endl;
67+ std::free(q);
68+ }
69+ ```
70+ ## 出力例
71+ ```
72+ 0 1 2 3 4 0 0 0 0 0
73+ ```
74+
75+
76+ ## 関連項目
77+ - [ ` calloc ` ] ( calloc.md ) : メモリを確保する
78+ - [ ` malloc ` ] ( malloc.md ) : メモリを確保し、領域をゼロ初期化する
79+ - [ ` free ` ] ( free.md ) : 確保したメモリを解放する
You can’t perform that action at this time.
0 commit comments