C++/C++ 기타

C++에서 new로 동적 메모리 할당 후 null값 체크를 해야 할까요?

kimc 2021. 7. 20. 23:57


 

이번 글을 통해 배워갈 내용

  1.  C++ 에서 new 선언 후에 nullptr 체크를 해줘야 하는지 여부

실무에서 작업을 하다보면 new 로 메모리 할당 후에 nullptr 체킹을 하는 프로그래머들을 가끔 봅니다.

 

c++에서 동적으로 메모리를 할당 하는 new 연산자는 많은 분들이 씁니다만

 

new 연산자를 사용하고 바로 다음에 nullptr 체크를 하는게 과연 올바른 방법일까요?

 

예시를 보여드리겠습니다.

 

#include <iostream>

using namespace std;

int main()
{
    int* pMyInt = new int;
    
    if(pMyInt == nullptr)
    {
        cout<<"nullptr";
    }
    else
    {
        cout<<"not nullptr";
    }
    
    

    return 0;
}

 

위와 같은 코드는

 

제 컴파일러에서

 

not nullptr를 출력합니다.

 

이는 new 를 통해 메모리가 할당되었기 때문에 nullptr가 아니기 때문입니다.

 

 

결론은

 

C++에서

 

고대 석기시대 컴파일러를 쓰는게 아니면

 

new를 사용해서 메모리를 할당하면

 

nullptr가 나오지 않기 때문에

 

nullptr 체킹을 해주지 않아도 된다고 대부분의 영어권 전문가 들이 말합니다.

 

아래 참조 및 인용 참조

 

 

 

 

참조 및 인용

 

https://www.cs.technion.ac.il/users/yechiel/c++-faq/new-never-returns-null.html

 

Do I need to check for NULL after p = new Fred()?, C++ FAQ

No! (But if you have an ancient, stone-age compiler, you may have to force the new operator to throw an exception if it runs out of memory.) It turns out to be a real pain to always write explicit NULL tests after every new allocation. Code like the follow

www.cs.technion.ac.il

 

https://en.cppreference.com/w/cpp/language/new

 

new expression - cppreference.com

Creates and initializes objects with dynamic storage duration, that is, objects whose lifetime is not necessarily limited by the scope in which they were created. [edit] Syntax ::(optional) new (placement_params)(optional) ( type ) initializer(optional) (1

en.cppreference.com

 

 

C++ Primer

 

 

 


https://codemasterkimc.tistory.com/35

 

C++ 이론을 배울수 있는 곳 정리

개요  C++을 배우는 책, 강의, 블로그, 링크 등을 공유합니다. (링크 및 간략한 설명을 하였으나 만약 원작자가 링크를 거는것을 원치 않을 경우 연락주시기 바랍니다.) 서적 https://www.amazon.com/Prime

codemasterkimc.tistory.com


 

728x90