이유:
동적으로 할당된 메모리의 경우 0xcdcdcdcd로 초기화 됨.
문제 되는 상황:
변수의 주소 값이 NULL (0x00000000)인 경우에 예외처리를 하도록 하면 0xcdcdcdcd로 초기화 된 변수의 경우 적용안됨.
보통 Pointer 변수를 선언하고 사용하기 전 if문으로 가드를 합니다.
하지만 많이 하는 실수 중 하나는 if문의 조건을 NULL인 경우만 건다는 점입니다.
동적으로 할당된 메모리의 주소를 가리키는 포인터 변수는 0xcdcdcdcd로 초기화 됩니다.
따라서 다음과 같은 두 가지의 방법으로 거를 수 있습니다.
방법 1:
//Example.h
#include <QPlainTextEdit>
class Example() {
public:
Example() {}
private:
QPlainTextEdit* m_member;
}
//Example.cpp
#include "Example.h"
Example::Example() : m_member(NULL) {}
int main() {
if (m_member == NULL) { return; }
}
방법 2:
//Example.h
#include <QPlainTextEdit>
class Example() {
public:
Example() {}
private:
QPlainTextEdit* m_member;
}
//Example.h
#include "Example.h"
Example::Example() {}
int main() {
if (m_member == NULL || m_member == 0xCDCDCDCD) { return; }
}
방법 1을 추천합니다.
'Develop > C++' 카테고리의 다른 글
[error] error C2360: initialization of 'variable' is skipped by 'case' label. (0) | 2023.04.11 |
---|---|
implicit declaration of function 'scanf_s' is invalid in C99 오류 (0) | 2021.12.29 |