Language Study/C

[C/C++] 10 - 01 메모리 동적 할당

지미닝 2022. 12. 6. 01:12

목차

  1. 정적인 메모리 공간 할당의 한계
  2. 동적인 메모리 할당 및 해제 함수
  3. assert 매크로
  4. 메모리 공간의 할당과 복사

1. 정적인 메모리 공간 할당의 한계

만약 이 코드에서 1의 값을 100이라 했을 때 만약에 입력한 값이 150이면 run-time error 가 발생하고, 10을 입력했다면 메모리를 불필요하게 낭비한게 됨

→  필요한 크기를 미리 알 수 없다!! 면...

 

2. 동적인 메모리 할당 및 해제 함수

Dynamic Memory Management Functions

  • Defined in header <stdlib.h>

메모리 동적 할당 함수

void *malloc(size t, size);

  • Allocates size bytes of uninitalized storage
  • Param: size - number of bytes to allocate
  • Return : On success, returns the pointer to the beginning of newly allocated memory. The returned pointer must be deallocated with free() or realloc(). On failure, returns a null pointer.

동적 할당 메모리 해제 함수

void free(void *ptr);

  • Deallocates the space previously allocated by malloc()
  • Param: ptr - pointer to the memory to deallocate
  • Return - none

3. assert 매크로

assert

  • 영어 단어: verb, if somone asserts a fact or belief, they state if irmly
  • 디버깅 시 특정 조건을 검사하는 메크로 함수
  • assert(수식); 형태로 사용함
    • Defined in <assert.h>
  • 프로그램 수행 중 '수식'이 거짓(False, 값은 0)이면 오류 메시지 출력 후 프로그램 종료

메모리 동적 할당을 포함하여 pointer 값 유효성 확인에 널리 사용

  • malloc()의 결과 포인터 값이 Null 이라면 오류 메시지 출력 후 프로그램 종료

assert 활용 시 고려 사항

  • assert 매크로는 전처리기로 무시하도록 조정할 수 있음
  • NDEBUG(no debug)를 선언하면 assert 매크로를 무시함
    • IDE환경에서 Release모드로 Build 하면 assert 매크로를 무시함
  • S/W 안정을 위해 디버깅이 끝난 후에도 assert를 남겨두는 것을 권고함

4. 메모리 공간의 할당과 복사

동적 할당 메모리의 초기값?

  • 초기화하지 않은 지역 변수가 garbage value라 불리는 알 수 없는 값을 가지듯 malloc()로 할당 받은 메모리 공간의 값도 garbage value를 가진다
  • calloc()을 이용하면 동적 할당 메모리 초기 값을 모두 0으로 설정할 수 있다.
    • line 13은 int 크기 항목 100개를 수용할 수 있는 메모리를 할당하고 그 값을 0으로 설정한다.

void *calloc(size_t num, size_t size);

  • allocates and zeroes memory
  • Param: num - number of objects, size - size of each object
  • Return: On success, returns the pointer to the beginning of newly allocated memory. On failure, returns a null pointer

void *memcpy(void *dest, const void *src, size_t count);

  • copies one sequential buffer to another
  • Param: dest - pointer to the object to copy to; scr - pointer to the object to copy from;
  • Return: Returns a copy of dest