Dynamic memory: malloc, free, and realloc · Memori dinamis: malloc, free, dan 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.
Memori stack vs memori heap
- Variabel lokal biasa tinggal di stack. Mereka muncul saat fungsi dimulai dan hilang saat fungsi selesai.
- Terkadang Anda membutuhkan memori yang bertahan lebih lama dari fungsi, atau ukurannya baru diketahui saat waktu berjalan.
- Memori itu berasal dari heap. Anda memintanya, dan nanti Anda mengembalikannya.
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 dan sizeof
mallocmeminta blok byte dari heap dan mengembalikan pointer ke sana.- Gunakan
sizeofuntuk mendapatkan ukuran satu item:malloc(n * sizeof(int))membuat ruang untuknints. - Blok tersebut milik Anda untuk digunakan melalui pointer, persis seperti array:
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 dan kebocoran memori
- Saat selesai menggunakan memori heap, kembalikan dengan
free(pointer). - Jika Anda tidak pernah
free-nya, program bocor memori — ia menyimpan ruang yang tidak lagi digunakan. - Aturan untuk tugas ini: fungsi Anda mengalokasikan dan mengembalikan; penguji membebaskannya. Jangan panggil
freesendiri.
#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.
Memperbesar array dengan realloc
realloc(a, newSize)mengubah ukuran blok heap, menjaga isi lama.- Ia mungkin memindahkan blok, jadi selalu gunakan nilai kembalian-nya:
a = realloc(a, ...). - Inilah cara memperbesar array satu item sekaligus, seperti daftar yang semakin panjang.
Common mistakes
- Every
mallocneeds a matchingfree; do not use memory afterfree. - Check that
mallocdid not returnNULL.
Kesalahan umum
- Setiap
mallocmemerlukanfreeyang sesuai; jangan gunakan memori setelahfree. - Pastikan
malloctidak mengembalikanNULL.
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.
Sekarang Anda coba
- Gunakan
malloc(n * sizeof(int))untuk array baru, dan#include <stdlib.h>. - Fungsi Anda mengembalikan pointer; pengecek akan membebaskannya — jangan panggil
free. Jangan tulismain.
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. · Lengkapi int *make_array(int n, int value) agar mengalokasikan n integer (dengan malloc), mengatur setiap elemennya menjadi value, dan mengembalikan pointer. Pengecek akan membebaskan memori ini. Jangan tulis fungsi main.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
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. · Lengkapi int *concat(const int a[], int na, const int b[], int nb) agar mengalokasikan na + nb integer, menyalin semua isi a lalu semua isi b, dan mengembalikan pointer. Pengecek akan membebaskannya. Jangan tulis kode main.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
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. · Lengkapi int *push(int *a, int *len, int value) agar memperbesar array tumpukan a untuk menampung satu integer lagi dengan realloc, menyimpan value di akhir, meningkatkan *len sebesar 1, dan mengembalikan pointer baru. Pengecek akan membebaskannya. Jangan tulis kode main.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.