C_C++/C_라이브러리_함수

(C언어) calloc: 메모리를 동적으로 할당 받기

고니자니 2023. 1. 31. 12:35
반응형

#calloc #동적메모리 #힙(heap) #free

 

 

#include <malloc.h>   // #include <stdlib.h>
void *calloc(size_t nitems, size_t size);

calloc 함수는 힙(head) 메모리 영역을 동적으로 할당받습니다.

nitems x size 만큼의 블록 크기를 할당하고, 할당된 블록을 0으로 초기화 시킵니다.

메모리를 할당 받았으면 할당된 블록의 포인터를 반환하고, 할당 받지 못했으면 NULL을 반환합니다.

할당된 블록은 free 함수로 해제합니다.

 

다음 예제는 입력받은 정수 n 갯수만큼 int 크기의 메모리를 할당받아, 값을 1,2,3...으로 설정한 후 출력하는 예를 보인것입니다.

 

#define _CRT_SECURE_NO_WARNINGS  // Visual Studio

#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main()
{
	int* p=NULL;
	int n;

	scanf("%d", &n);

	p = (int *)calloc(n, sizeof(int));
	if (p == NULL)
		return -1;

	for (int i = 0; i < 100; i++)
		p[i] = i + 1;

	for (int i = 0; i < 100; i++)
		printf("%d ", p[i]);
	printf("\n");

	free(p);

	return 0;
}

 

 

다음 예제는 char 형 포인터를 할당받은 예제 입니다.

#define _CRT_SECURE_NO_WARNINGS  // Visual Studio


#include <stdio.h>
#include <malloc.h>

int main(void)
{
    char* buffer;

    buffer = (char*)calloc(100, sizeof(char));
    if (buffer != NULL)
    {   
        strcpy(buffer, "100바이트의 메모리를 할당 받았습니다.");
        printf("%s\n", buffer);
    }
    else
        printf("메모리를 할당 받지 못했습니다.\n");
    free(buffer);
    return 0;
}

 

 

참고: calloc, malloc, free, realloc

반응형