[C] memAlloc / memFree / 메모리 할당, 해제

2021. 6. 18. 15:29🧑🏻‍💻/C & C++

 

1. 기본적으로 할당 / 해제 하는 방법

2. 함수를 만들어, 사용하여 할당 / 해제 하는 방법.

* 반드시 메모리누수를 생각해 Free 해 줄 것.

#include <stdio.h>
#include <stdlib.h>
#define ALLOC_SIZE 80
char* memAlloc(int size)
{
char* tempAllocMem = (char*)malloc(sizeof(char) * size);
printf("Allocate : 0x%x \r\n", (unsigned int)tempAllocMem);
return tempAllocMem;
}
void memFree(char* address)
{
printf("Freed : 0x%x \r\n", (unsigned int)address);
free(address);
}
void functionCheck(void)
{
char* testMem = NULL;
printf("Memory Allocation Test \r\n");
testMem = memAlloc(sizeof(char) * ALLOC_SIZE);
snprintf(testMem, sizeof("Hello, World"), "Hello,World!!!");
printf("%s \r\n", testMem);
memFree(testMem);
}
void main(void)
{
char* testMem = NULL;
testMem = (char*)malloc(sizeof(char) * ALLOC_SIZE);
printf("Memory Allocation Test \r\n");
snprintf(testMem, sizeof("test, Mem"), "test, Mem");
printf("%s \r\n", testMem);
free(testMem);
printf("\r\n funtion check \r\n");
functionCheck();
}

 

결과 값

 

 

 

[C] 2차원 배열 malloc / free / 메모리 할당과 해제

malloc - memory allocation 메모리 할당 free - free~~~~~~~~~~~~~~~ 메모리 해제 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 //SizeOfArray : 만들고 싶은 배열의 원소의 수 //메모리 할당해제 : 메모리 누..

chanhhh.tistory.com