Dynamic memory: malloc, free, and realloc · Dung lượng động: malloc, free, và 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.
Bộ nhớ Stack vs Bộ nhớ Heap
- Các biến cục bộ thông thường tồn tại trên stack. Chúng xuất hiện khi hàm bắt đầu và biến mất khi hàm kết thúc.
- Đôi khi bạn cần bộ nhớ vượt thời gian sống của hàm, hoặc kích thước của nó chỉ biết khi chạy chương trình.
- Bộ nhớ đó lấy từ heap. Bạn yêu cầu nó, và sau đó bạn trả lại nó.
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 và sizeof
mallocyêu cầu từ heap một khối byte và trả về một con trỏ đến nó.- Sử dụng
sizeofđể lấy kích thước của một mục:malloc(n * sizeof(int))tạo không gian chonint. - Khối bộ nhớ thuộc quyền sử dụng của bạn thông qua con trỏ, giống hệt như một mảng:
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 và rò rỉ bộ nhớ
- Khi bạn hoàn thành việc sử dụng bộ nhớ heap, hãy trả lại nó bằng
free(pointer). - Nếu bạn không bao giờ
freenó, chương trình sẽ rò rỉ bộ nhớ — nó giữ lại không gian không còn sử dụng nữa. - Quy tắc cho các bài tập này: hàm của bạn phân bổ và trả về; trình kiểm tra sẽ giải phóng nó. Đừng tự gọi
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.
Mở rộng mảng với realloc
realloc(a, newSize)thay đổi kích thước một khối bộ nhớ heap, giữ nguyên nội dung cũ.- Nó có thể di chuyển khối bộ nhớ, vì vậy hãy luôn sử dụng giá trị trả về của nó:
a = realloc(a, ...). - Đây là cách bạn mở rộng mảng thêm một phần tử mỗi lần, giống như một danh sách dài ra.
Common mistakes
- Every
mallocneeds a matchingfree; do not use memory afterfree. - Check that
mallocdid not returnNULL.
Lỗi thường gặp
- Mỗi
malloccần mộtfreetương ứng; không sử dụng bộ nhớ sau khi gọifree. - Kiểm tra xem
malloccó trả vềNULLhay không.
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.
Bây giờ bạn thử
- Sử dụng
malloc(n * sizeof(int))để tạo mảng mới, và#include <stdlib.h>. - Hàm của bạn trả về con trỏ; trình kiểm tra sẽ giải phóng nó — đừng gọi
free. Đừng viết một hàmmain.
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. · Hoàn thành int *make_array(int n, int value) để phân bổ n int (với malloc), gán mọi phần tử bằng value, và trả về con trỏ. Bộ kiểm tra sẽ giải phóng bộ nhớ này. Không viết một main.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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. · Hoàn thành int *concat(const int a[], int na, const int b[], int nb) để phân bổ na + nb int, sao chép tất cả các phần tử của a sau đó tất cả các phần tử của b, và trả về con trỏ. Bộ kiểm tra sẽ giải phóng bộ nhớ này. Không viết một main.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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. · Hoàn thành int *push(int *a, int *len, int value) để mở rộng mảng heap a thêm một int với realloc, lưu value vào cuối mảng, tăng *len lên 1, và trả về con trỏ mới. Bộ kiểm tra sẽ giải phóng bộ nhớ này. Không viết một main.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.