#include <stdio.h>
#include <stdlib.h>

int main()
{
	int *ptr;

	if (ptr)	//에러 발생
		printf("ptr is not null");
    
	ptr = (int*)malloc(sizeof(int) * 3);
	ptr[0] = 0;
    
	free(ptr);

	if (ptr)	//에러가 발생하지 않음
		printf("ptr is not null : %d", ptr[0]);	//실행됨
        
    return 0;
}

 

8번 라인에서 포인터 변수를 초기화하지 않고 사용을 하면 에러가 발생한다.

malloc을 이용해 int *3 만큼의 메모리 할당을 한 뒤 free를 이용해 할당을 해지하고 ptr을 이용해 데이터에 접근한다면 에러가 발생하지 않는다.

 

이는 free를 하면 할당 되었던 메모리에 다른 포인터가 접근 가능하게 하는 것이지 메모리의 내용을 지우는 것이 아니기 때문에 여전히 그 메모리 공간에 데이터가 그대로 남아있기 때문이다.

 

안전하게 free를 이용하기 위해선 다음과 같은 방식을 이용해 free한 포인터를 이용해 해당 메모리의 접근을 막으면 된다.

#include <stdio.h>
#include <stdlib.h>

int main()
{
	int *ptr;

	ptr = (int*)malloc(sizeof(int) * 3);
	ptr[0] = 0;
    
   	 if(ptr)
 	 {
   		  free(ptr);
   		  ptr = NULL;
 	 }
        
    return 0;
}

 

+ Recent posts