동적 메모리 할당과 해제
배열의 크기를 컴파일 하는 시점에서 정하지 않고 프로그램이 실행되는 시점에서 정하려면 메모리 공간을 동적으로 할당받아서 사용해야 한다 .
함수가 호출될 때 사용되는 지역 변수들은 스택 메모리 영역에 할당하지만 동적으로 할당받는 메모리는 힙 메모리 영역에 할당된다.
1 2 | #include <stdlib.h> void *malloc(size_t size); | cs |
동적으로 메모리를 할당받기 위해서는 malloc() 함수를 호출한다 .
동적으로 할당받기를 원하는 데이터 크기를 매개변수로 전달하면서 malloc() 함수를 호출하면 동적으로 할당 된 메모리의 시작 주소값이 리턴된다.
할당된 메모리 공간은 직접 해제하지 않으면 프로그램이 종료될 때 할당된 메모리 공간이 해제된다.
할당된 메모리 공간을 해제하지 않고 지속적으로 할당만을 받아서 사용하게 되면 메모리 누스(Memory leak)이 발생하게 된다 .
동적으로 할당된 메모리는 반드시 해제를 해줘야 하며 해제하는 방법은 free() 함수를 호출해야한다 .
1 2 | #include <stdlib.h> void free(void *ptr); | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char *ptr = (char *)malloc(10); strcpy(ptr, "Hello"); printf("%s\n" ,ptr); free(ptr); return 0; } | cs |
12행에서 free 함수를 이용해서 메모리 공간을 해제하였다 .
calloc() 함수
num * size 바이트의 메모리를 힙 메모리 영역에서 동적으로 할당하고 할당된 메모리의 시작 주소값을 반환한다
1 2 3 | #include <stdlib.h> void *calloc(size_t nmemb, size_t size); | cs |
예제 )
1 2 3 4 5 6 7 8 9 10 11 12 | #include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int*)calloc(sizeof(int), 10); free(ptr); return 0; } | cs |
메모리 영역을 동적으로 할당하는 소스
자료형의 크기를 * 10 으로 총 40바이트를 할당하고 해제하는 소스이다 .
memeset() 함수
1 2 3 | #include <string.h> void *memset(void *s, int c, size_t n); | cs |
메모리 영역을 특정한 값으로 쓰는 함수로 대부분 메모리 영역을 특정한 값으로 초기화 하는데 사용된다.
s부터 n개의 바이트를 c로 채운다
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <stdio.h> #include <string.h> int main() { int i; char p[5]; memset(p, 0x11 , 5); for(i = 0; i < 5; i++) { printf("p[%d]:%x\n",i,p[i]); } return 0; } |
memcmp() 함수
1 2 | #include <string.h> int memcmp(const void *s1, const void *s2, size_t n); |
memcmp() 함수는 s1과 s2의 처음 n 바이트를 비교하고 그 차이를 리턴한다
만약 s1과 s2가 처음부터 n바이트의 데이터가 같을시에 0 을 리턴하고 일치하지 않으면 그 차이를 리턴한다
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <stdio.h> #include <stdlib.h> int main() { const char *s1 = "helloworld"; const char *s2 = "hello"; if(!memcmp(s1,s2,5)) { printf("%c %c %c %c %c\n", s1[0],s1[1],s1[2],s1[3],s1[4]); printf("%c %c %c %c %c\n", s2[0],s2[1],s2[2],s2[3],s2[4]); } return 0; } | cs |
memcpy() 함수
src 주소의 메모리에 있는 데이터를 시작주소에서 n바이트만큼 dest 주소로 복사하는 역할을 한다
1 2 | #include <string.h> void *memcpy(void *dest, const void *src, size_t n); |
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <stdio.h> #include <string.h> int main() { char buf[100]; char *str = "hello!! wordl!!"; memcpy(buf, str, strlen(str) +!); printf("buf :%S\n",buf); return 0; } | cs |