Dynamic memory: malloc, free, and realloc
Stack memory vs heap memory
- Normal local variables live on the stack. They appear when a function starts and vanish when it returns.
- Sometimes you need memory that outlives the function, or whose size you only know at run time.
- That memory comes from the heap. You ask for it, and later you give it back.
スタックメモリ vs ヒープメモリ
- 通常のローカル変数はスタック上に存在します。関数が開始すると現れ、終了すると消えます。
- 時折、関数の寿命を超えて残るメモリが必要だったり、サイズを実行時にしか分からない場合があったりします。
- そのメモリはヒープから取得します。要求して、後に返します。
malloc and sizeof
mallocasks the heap for a block of bytes and returns a pointer to it.- Use
sizeofto get the size of one item:malloc(n * sizeof(int))makes room fornints. - The block is yours to use through the pointer, exactly like an array:
a[0],a[1], ...
malloc と sizeof
mallocはヒープからバイトブロックを要求し、そこへのポインタを返します。sizeofを使って1個あたりのサイズを取得します:malloc(n * sizeof(int))はn個のint分のスペースを作ります。- ポインタを通じてこのブロックを使用でき、配列と同じように:
a[0],a[1], ...
free and memory leaks
- When you are done with heap memory, give it back with
free(pointer). - If you never
freeit, the program leaks memory — it holds space it no longer uses. - Rule for these tasks: your function allocates and returns; the checker frees it. Do not call
freeyourself.
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
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;
}
Growing an array with realloc
realloc(a, newSize)resizes a heap block, keeping the old contents.- It may move the block, so always use its return value:
a = realloc(a, ...). - This is how you grow an array one item at a time, like a list that gets longer.
realloc による配列の拡張
realloc(a, newSize)はヒープブロックのサイズを変更し、古い内容も維持します。- ブロックが移動することがあるので、必ず戻り値を使用します:
a = realloc(a, ...)。 - リストが長くなるように、これを1つずつ増やす方法です。
Common mistakes
- Every
mallocneeds a matchingfree; do not use memory afterfree. - Check that
mallocdid not returnNULL.
よくあるミス
mallocには対応するfreeが必要です;free以後のメモリの使用は避けてください。mallocがNULLを返していないか確認してください。
Now you try
- Use
malloc(n * sizeof(int))for new arrays, and#include <stdlib.h>. - Your function returns the pointer; the checker frees it — do not call
free. Do not write amain.
あなたも試してみよう
- 新しい配列には
malloc(n * sizeof(int))を使用し、#include <stdlib.h>は使用しないでください。 - 関数はポインタを返します。チェックツールがそれを解放するため、
freeを呼び出さないでください。また、mainを記述しないでください。
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 not write a main.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
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 not write a main.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
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 not write a main.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。