C free() 할당받은 메모리를 반환 함수
malloc()이나 calloc()에서 할당받은 메모리를 시스템에 반환합니다. 포인터 값이 NULL이면 작업을 취소합니다.
- 헤더: stdlib.h
- 형태: void free( void *ptr)
- 인수: void *ptr 메모리를 해제할 포인터
- 반환: -
참고로 말씀드리면 free()의 인수는 당연히 메모리를 할당받은 포인터를 넘겨주어야 합니다. 그러나 여기서 free()를 호출한 후에 포인터의 주소 값이 NULL로 초기화 되질 않습니다. 그러므로 이 변수를 다시 free()로 호출하면,
*** glibc detected *** double free or corruption (top): 0x08d34008 ***
중지됨
에러가 발생되어 프로그램이 중지됩니다. 이런 문제를 해결하기 위해서 free() 후에는 포인터 변수를 NULL로 초기화해 주는 것이 좋습니다.
C언어 free() 함수 예제
#include <stdio.h>
#include <stdlib.h>
int main( void)
{
int *ptr_int1;
int *ptr_int2;
int ndx;
ptr_int1 = (int *)malloc( 50 *sizeof( int));
ptr_int2 = (int *)calloc( 50, sizeof( int));
for ( ndx= 0; ndx < 50; ndx++)
{
ptr_int1[ndx] = 2007 +ndx;
ptr_int2[ndx] = 2007 +ndx;
}
for ( ndx= 0; ndx < 50; ndx++)
{
printf( "%d %d\n", ptr_int1[ndx], ptr_int2[ndx]);
}
free( ptr_int1);
free( ptr_int2);
ptr_int1 = NULL;
ptr_int2 = NULL;
return 0;
}
C언어 free() 예제 실행 결과
]$ ./a.out
2007 2007
2008 2008
2009 2009
2010 2010
2011 2011
2012 2012
중략
2051 2051
2052 2052
2053 2053
2054 2054
2055 2055
2056 2056
]$
'컴퓨터 > 프로그래밍' 카테고리의 다른 글
C언어 realloc 함수 동적 메모리 크기 변경 (0) | 2020.03.12 |
---|---|
C언어 calloc 함수 요소 크기 지정 동적 메모리 할당 (2) | 2020.03.12 |
C언어 malloc 함수 동적 메모리 할당 (0) | 2020.03.12 |