-
[자료구조] 1-2. 동적 메모리 Dynamic memory (C/C++)50 shades of ZZ/C(++) 자료구조 마스터 2023. 9. 27. 01:42728x90728x90
Dynamic memory 동적 메모리
- static / dynamic memory
- sray : pointer constant (<> pointer)
- pary : pointer variable
void Pointer_Test(void){ int sary[5]; int *pary = NULL; pary = (int *)malloc(5 * sizeof(int)); }
- dynamic memory allocation
- 프로그램 실행 전에 필요한 메모리를 알 수 없는 경우
- 동일한 일을 반복하는 프로그램에서 같은 이름으로 서로 다른 크기의 메모미를 매번 필요로 하는 경우
// allocation 함수 (형변환하여 호출) void *malloc(size_t size); // 전체 크기 void *calloc(size_t number, size_t size); // 요소 개수, type 크기 void *realloc(void *memblock, size_t size); // 이전 메모리, 새로운 크기 // deallocation 함수 void free(void *memblock); // 할당 취소하고자 하는 메모리
- allocation error 대비 (memory 부족 시 NULL 반환 → 대비 코드 필요)
void Pointer_Test(void){ int *pary; if (!(pary = (int*)malloc(5 * sizeof(int)))){ fprintf(stderr, "Insufficient memory"); exit(EXIT_FAILURE); // exit program } // EXIT_SUCCESS = 0 // EXIT_FAILURE = 1 }
if문 조건 해설
- pary에 malloc의 return pointer를 저장
- pary가 TRUE가 아닌지 확인 ⇒ ”pary가 NULL 이면”
MACRO 활용한 자동화
- 4줄 코드를 1줄로 축약 가능
#define MALLOC(ptr, type, size) \\ if (!((ptr)=(type)malloc(size))){ \\ fprintf(stderr, "Insufficient memory"); \\ exit(EXIT_FAILURE); } void Pointer_Test(void){ int *pary; MALLOC(pary, int *, 100 * sizeof(int)) }
2D memory allocation
#define MALLOC(ptr, type, size) \\ if (!((ptr)=(type)malloc(size))){ \\ fprintf(stderr, "Insufficient memory"); \\ exit(EXIT_FAILURE); } void Pointer_Test(void){ int **pary2 = NULL; int R = 4, C = 6; // 2D allocation MALLOC(pary2, int **, R * sizeof(int *)) for(int i = 0; i < R; i++){ MALLOC(pary2[i], int *, C * sizeof(int)) } // free routine for(int i = 0; i < R; i++){ free(pary2[i]); } free(pary2); pary2 = NULL; // 혹시 모를 변수 대응 }
2023.09.26 - [50 shades of ZZ/C(++) 자료구조 마스터] - [자료구조] C/C++ 자료구조 마스터(?)를 위한 요점 정리
728x90728x90'50 shades of ZZ > C(++) 자료구조 마스터' 카테고리의 다른 글
[자료구조] 1-3. 알고리즘 예시 & 재귀 함수 (C/C++) (0) 2023.09.27 [자료구조] C/C++ 자료구조 마스터(?)를 위한 요점 정리 (0) 2023.09.26 [자료구조] 1-1. 포인터 Pointer (C/C++) (0) 2023.09.26 - static / dynamic memory