From c46ae607801797a5f969de7fca90869cdaf4043e Mon Sep 17 00:00:00 2001 From: Peace Date: Thu, 24 Apr 2025 10:50:10 +0900 Subject: [PATCH] malloc, free --- basic/4_memoryManagement.c | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 basic/4_memoryManagement.c diff --git a/basic/4_memoryManagement.c b/basic/4_memoryManagement.c new file mode 100644 index 0000000..fc79911 --- /dev/null +++ b/basic/4_memoryManagement.c @@ -0,0 +1,32 @@ +#include +#include + +int main() +{ + const int COUNT = 5; + + // 동적 메모리 할당, ptr에 동적으로 할당된 메모리의 시작주소 저장 + int *ptr = (int*)malloc(sizeof(int) * COUNT); + if (!ptr) + { + printf("Fail to malloc\n"); + return 1; + } + + for (int i = 0; i < COUNT; i++) + { + ptr[i] = i * 10; // 값 초기화 + printf("%d ", ptr[i]); // 값 출력 + } + printf("\n"); + + free(ptr); + + printf("\n"); + for (int i = 0; i < COUNT; i++) + { + printf("%d ", ptr[i]); // 값 출력 + } + + return 0; +} \ No newline at end of file