C/C언어 문법

realloc 함수 사용시 주의 해야할 점!!

lwj789 2021. 7. 1. 00:29

realloc함수는 동적할당된 메모리의 크기를 변경해주는 함수입니다.

메모리 크기를 변경할 경우 기존에 사용하고 있던 메모리 주소가 유지 되면서 크기 변화를 합니다. 하지만 기존의 주소에서 시작해서 변경한 크기 만큼 연속되게 메모리 공간을 확보할 수 없다면 해당 주소는 버리고 다른 공간에서 변경한 크기만큼 메모리를 확보합니다.

그렇기 때문에 이렇게 재할당된 메모리 주소는 변경되게 됩니다.

주소만 달라졌을 뿐 기존에 가지고 있던 내용은 그대로 유지 됩니다.

예제코드.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void main()
{
    char *p_org = NULL*p_new = NULL;    
    char *str = "Dev_jong";
 
    // 9바이트 크기의 메모리를 할당한다. (처음에는 p_new, p_org가 같은 값을 가진다.)
    unsigned int len = strlen(str)+1;
    p_new = p_org = (char *)malloc(len);
    strcpy_s(p_new, len, str);    
    
    // p_new, p_org 변수에 저장된 주소와 문자열을 출력한다.
    printf("새로운 주소 : %p, 원본 주소 : %p (%s)\n", p_new, p_org, p_new);
    
    // 최대 100번을 반복하면서 주소가 바뀌는지 체크한다.
    for (int retry = 0; retry < 100 && p_org == p_new; retry++) {
        unsigned int _len = len * (retry + 2);
        p_new = (char *)realloc(p_new, _len);
        
        strcpy_s(&p_new[retry * len], len, str);
 
        // p_new, p_org 변수에 저장된 주소와 문자열을 출력한다.
        printf("[%d] 새로운 주소 : %p, 원본 주소 : %p (%s)\n", retry + 1, p_new, p_org, &p_new[retry * 9]);
    }
    
    printf("\n\n");
    printf("출력1 : %s, 출력2 : %s\n"&p_new[10], &p_org[10]);
 
    // 할당된 메모리를 해제환다.
    free(p_new);
}
cs

 

 

 

결과