Dynamic memory: malloc, free, and realloc · 동적 메모리: malloc, free 및 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를 사용하십시오: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)로 돌려주십시오. - 만약 NEVER
free를 하지 않으면, 프로그램이 메모리를 **누수(leaks)**시킵니다 — 더 이상 사용하지 않는 공간도 유지합니다. - 이 작업들의 규칙: 당신의 함수가 할당하고 반환하며, 체크러가 freeing합니다. 스스로
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, ...). - 이는 한 번에 한 항목씩 배열을 확장하는 방법입니다, 길어지는 목록과 같습니다.
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. · int *make_array(int n, int value)을 완성하여 n개의 int를 할당하고(malloc 포함), 모든 요소를 value로 설정한 후 포인터를 반환하십시오. 체크러가 이를 해제합니다. **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. · int *concat(const int a[], int na, const int b[], int nb)을 완성하여 na + nb개의 int를 할당하고, a의 모든 요소를 복사한 뒤 b의 모든 요소를 복사한 후 포인터를 반환하십시오. 체크러가 이를 해제합니다. **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. · int *push(int *a, int *len, int value)을 완성하여 힙 배열 a을 realloc로 확장하여 int를 하나 더 저장하게 하고, 끝부분에 value을 저장하며, *len를 1만큼 증가시켜 새 포인터를 반환하십시오. 체크러가 이를 해제합니다. **main**을 작성하지 마십시오.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.