スタックメモリ vs ヒープメモリ
- 通常の非静的ローカル変数は自動ストレージ期間を持ち、そのスコープが終了すると寿命が終わる。実装通常はそれらをスタック上に配置しますが、Cは特定のメモリレイアウトを要求しません。
- 時折、関数の寿命を超えて残るメモリが必要だったり、サイズを実行時にしか分からない場合があったりします。
- そのメモリはヒープから取得します。要求して、後に返します。
malloc と sizeof
mallocはヒープからバイトブロックを要求し、そこへのポインタを返します。- 単一項目のサイズを取得するには
sizeofを使用します:malloc(n * sizeof(int))はn個の int を格納するための領域を要求します。使用前にNULLのチェックを行い、新規割り当てされた値は初期化されていません。今回はサイズが小さく正の値であるため、バイト計算は問題ありません。 - ポインタを通じてこのブロックを使用でき、配列と同じように:
a[0],a[1], ...
free とメモリーリーク
- ヒープメモリ的使用结束后,使用
free(pointer)将其归还。 - 一度も
freeを使わないと、プログラムはメモリをリークします — 不再使用的空间を保持してしまいます。 - これらのタスクのルール: あなたの関数が割り当てて返す;チェッカー側がfreeします。 自分で
freeを呼び出さないでください。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = malloc(3 * sizeof(int)); // room for 3 ints
if (a == NULL) return EXIT_FAILURE;
a[0] = 5; a[1] = 6; a[2] = 7;
printf("%d\n", a[0] + a[1] + a[2]); // 18
free(a); // give it back
return 0;
}
realloc による配列の拡張
- 正の バイトサイズに対して、
realloc(a, newSize)が成功した場合は最初のmin(oldSize, newSize)バイトを保持します。新規に追加されたセルには初期化が必要です。 - 失敗した場合は
NULLを返して、古い割り当てを維持します。結果を一時的なポインタに保存してください。唯一のポインタにNULLを上書きすると、古いブロックへのアクセスを失います。 - 成功した場合は返されたポインタのみを使用する:ブロックが移動している可能性がある。ここではゼロサイズの
reallocを避けること。Cのバージョンによってそのルールは異なるためである。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = malloc(2 * sizeof *a);
if (a == NULL) return EXIT_FAILURE;
a[0] = 4; a[1] = 9;
int *grown = realloc(a, 3 * sizeof *a);
if (grown == NULL) {
free(a); // the old allocation still belongs to us
return EXIT_FAILURE;
}
a = grown;
a[2] = 16;
printf("%d %d %d\n", a[0], a[1], a[2]); // 4 9 16
free(a);
return 0;
}
よくあるミス
mallocには対応するfreeが必要です;free以後のメモリの使用は避けてください。- デレファレンスする前に割り当て結果を確認すること。成長に失敗しても、記録された長さを変えたり、呼び出し元の古い配列を解放したりしてはいけない。
あなたも試してみよう
- 新しい配列には
malloc(n * sizeof(int))を使用し、#include <stdlib.h>は使用しないでください。 - 関数はポインタを返します。チェックツールがそれを解放するため、
freeを呼び出さないでください。また、mainを記述しないでください。
難易度 4/5 · 280 コイン + 今日初回達成時の小ボーナス
Complete int *make_array(int n, int value) so it allocates n ints (with malloc), sets every one to value, and returns the pointer. The checker frees it. Do ~ではない write a main. Here 1 ≤ n ≤ 1000. If allocation fails, return NULL without accessing any elements.
実行ボタンをクリックして出力を確認してください。
難易度 4/5 · 280 コイン + 今日初回達成時の小ボーナス
Complete int *concat(const int a[], int na, const int b[], int nb) so it allocates na + nb ints, copies all of a then all of b, and returns the pointer. The checker frees it. Do ~ではない write a main. Lengths are non-negative and their sum is 1 to 1000. Leave both inputs unchanged; return NULL on allocation failure.
実行ボタンをクリックして出力を確認してください。
難易度 4/5 · 280 コイン + 今日初回達成時の小ボーナス
Complete int *push(int *a, int *len, int value) so it grows the heap array a to hold one more int with realloc, stores value at the end, increases *len by 1, and returns the new pointer. The checker frees it. Do ~ではない write a main. Here 0 ≤ *len < 1000. On allocation failure return NULL, leaving the old allocation and *len unchanged. The caller keeps its old pointer until it checks your result.
実行ボタンをクリックして出力を確認してください。