기능 malloc() 그리고 콜록() 동적으로 메모리를 할당하는 라이브러리 함수입니다. 동적이란 런타임(프로그램 실행) 중에 힙 세그먼트에서 메모리가 할당된다는 의미입니다.
초기화
malloc() 주어진 크기(바이트 단위)의 메모리 블록을 할당하고 블록의 시작 부분에 대한 포인터를 반환합니다. malloc()은 할당된 메모리를 초기화하지 않습니다. 먼저 초기화하지 않고 할당된 메모리에서 읽으려고 하면 정의되지 않은 동작이 호출됩니다. 이는 일반적으로 읽은 값이 가비지 값이 됨을 의미합니다.
C에서 배열을 사용하는 구조
콜록() 메모리를 할당하고 할당된 메모리의 모든 바이트를 0으로 초기화합니다. 초기화하지 않고 할당된 메모리의 값을 읽으려고 하면 이미 calloc()에 의해 0으로 초기화되었기 때문에 0을 얻게 됩니다.
매개변수
malloc()은 단일 인수를 취합니다. 할당할 바이트 수입니다.
malloc()과 달리 calloc()은 두 가지 인수를 사용합니다.
- 할당할 블록 수입니다.
- 각 블록의 크기(바이트)입니다.
반환 값
malloc() 및 calloc()에서 성공적으로 할당된 후 메모리 블록에 대한 포인터가 반환되고 그렇지 않으면 실패를 나타내는 NULL이 반환됩니다.
예
아래 C 코드는 동적 메모리를 할당하기 위한 malloc과 calloc 함수의 차이점을 보여줍니다.
씨
// C code that demonstrates the difference> // between calloc and malloc> #include> #include> int> main()> {> >// Both of these allocate the same number of bytes,> >// which is the amount of bytes that is required to> >// store 5 int values.> >// The memory allocated by calloc will be> >// zero-initialized, but the memory allocated with> >// malloc will be uninitialized so reading it would be> >// undefined behavior.> >int>* allocated_with_malloc =>malloc>(5 *>sizeof>(>int>));> >int>* allocated_with_calloc =>calloc>(5,>sizeof>(>int>));> >// As you can see, all of the values are initialized to> >// zero.> >printf>(>'Values of allocated_with_calloc: '>);> >for> (>size_t> i = 0; i <5; ++i) {> >printf>(>'%d '>, allocated_with_calloc[i]);> >}> >putchar>(>'
'>);> >// This malloc requests 1 terabyte of dynamic memory,> >// which is unavailable in this case, and so the> >// allocation fails and returns NULL.> >int>* failed_malloc =>malloc>(1000000000000);> >if> (failed_malloc == NULL) {> >printf>(>'The allocation failed, the value of '> >'failed_malloc is: %p'>,> >(>void>*)failed_malloc);> >}> >// Remember to always free dynamically allocated memory.> >free>(allocated_with_malloc);> >free>(allocated_with_calloc);> }> |
>
>
js의 전역 변수산출
Values of allocated_with_calloc: 0 0 0 0 0 The allocation failed, the value of failed_malloc is: (nil)>
C에서 malloc()과 calloc()의 차이점
차이점을 표 형식으로 살펴보겠습니다.
| 예 아니오. | malloc() | 콜록() |
|---|---|---|
| 1. | malloc()은 고정된 크기의 메모리 블록 하나를 생성하는 함수입니다. | calloc()은 지정된 수의 메모리 블록을 단일 변수에 할당하는 함수입니다. |
| 2. | malloc()은 하나의 인수만 취합니다. | calloc()은 두 개의 인수를 사용합니다. |
| 삼. | malloc()은 calloc보다 빠릅니다. | calloc()은 malloc()보다 느립니다. |
| 4. | malloc()은 시간 효율성이 높습니다. | calloc()은 시간 효율성이 낮습니다. |
| 5. | malloc()은 메모리 할당을 나타내는 데 사용됩니다. | calloc()은 연속적인 메모리 할당을 나타내는 데 사용됩니다. |
| 6. | 구문 : void* malloc(size_t size); | 구문 : void* calloc(size_t num, size_t size); |
| 8. | malloc()은 메모리를 0으로 초기화하지 않습니다. | calloc()은 메모리를 0으로 초기화합니다. |
| 9. | malloc()은 추가 메모리 오버헤드를 추가하지 않습니다. | calloc()은 추가 메모리 오버헤드를 추가합니다. |