Skip to content

Instantly share code, notes, and snippets.

@kciter
Created March 6, 2014 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kciter/9387956 to your computer and use it in GitHub Desktop.
Save kciter/9387956 to your computer and use it in GitHub Desktop.
댕글링 포인터 해결방법

댕글링 포인터란 이미 해제된 메모리를 가리키고 있는 포인터를 뜻한다.

#include <stdio.h>
int main() {
    int *p = (int*)malloc(sizeof(int));
    free(p); // p는 댕글링 포인터
    p = 1; // 이미 해제했기 때문에 에러가 발생
}

위와 같은 상황을 방지하기 위해서는 아래와 같이 해제한 포인터를 NULL값으로 바꿔준다.

#include <stdio.h>
int main() {
    int *p = (int*)malloc(sizeof(int));
    free(p); // p는 댕글링 포인터
    p = NULL;
    if (p != NULL) {
        p = 1; // p는 NULL이기 때문에 if문을 실행하지 않는다
    }
}

최근 C++에서는 상수 0을 define한 NULL 대신 nullptr가 등장하였다.

#include <stdio.h>
int main() {
    int *p = new int;
    delete p; // p는 댕글링 포인터
    p = nullptr;
    if (p != nullptr) {
        p = 1; // p는 nullptr이기 때문에 if문을 실행하지 않는다
    }
}

해당 작업을 매크로 혹은 inline함수로 제작하여 사용하면 편리하다.

#define SAFE_DELETE(a) if( (a) != NULL ) delete (a); (a) = NULL;
template <typename T>
inline void safe_delete(T*& p)
{
    delete p;
    p = static_cast<T *>(0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment