반응형

출처: http://thinkpro.tistory.com/67


포인터로 받은 주소에 할당된 메모리를 해제하는 함수를 작성했다.

당연히 해제된 메모리를 가진 포인터는 NULL 포인터가 할당되었을 거라고 생각했는데

막상 해보니 NULL이 아니였다.


struct SAMPLE {
	char* name;
	int no;
} typedef sample;

sample* global;

void maker() {
	global = (sample*) malloc(sizeof(sample));
}

void dangler() {
	sample* fun_local;

	fun_local = global;

	free(fun_local);

}

int main() {
	maker();
	dangler();

	if (global == NULL) {
		printf("global is NULL\n");
	} else {
		printf("global is not NULL\n");
	}

	return 0;
}

여기엔 두 가지 원인이 있었다.

첫 번째로

fun_local = global;
에서 global 변수가 아닌 global 변수의 사본을 사용하기 떄문이다.

그래서 이를 포인터로 값을 받게 수정하였다.

두 번째로 free() 함수를 부른 뒤에 그 포인터는 NULL 포인터가 아닌 다른 정의되지 않은 포인터 값이 들어가기 때문이다.

그러므로 free() 함수를 부른 뒤에 해당 포인터에 NULL 포인터를 직접 지정해줘야 했다.

struct SAMPLE {
	char* name;
	int no;
} typedef sample;

sample* global;

void maker() {
	global = (sample*) malloc(sizeof(sample));
}

void dangler() {
	sample** fun_local;

	fun_local = &global;

	free(*fun_local);
	*fun_local = NULL;

}

int main() {
	maker();
	dangler();

	if (global == NULL) {
		printf("global is NULL\n");
	} else {
		printf("global is not NULL\n");
	}

	return 0;
}


그래서 fun_local 변수를 global 변수의 주소값을 받게 수정하고,

free() 함수 호출 후 fun_local 변수에 NULL 포인터를 지정했더니 원하는대로 동작하였다.


반응형
Posted by 애콜라이트
l

free counters