2021年3月12日 星期五

[Code Review] Check pointer not null

  • C 語言有非常強大的 pointer, 但也因此惡名昭彰
  • 兩個常用的情況是
    • Null pointer check
      •     	if (ptr != NULL) {
                	// do something ...
                } else {
                	// error handling
                }
            
      • 其中就相當多可以討論的地方
        • 要用 if (ptr) 還是 if (ptr != NULL) 還是 if (NULL != ptr)
        • 建議使用 if (ptr) 就好, 幾個理由如下
          • If (ptr ==) 類型的 check, 可能會少寫一個 =, 變成 assignment, 造成難追的 bug
          • NULL 的 implementation 未明確定義, 依不同 compiler 可能實作成 ((char *)0), ((void *) 0), 0, 0L 等
          • 相容於 smart pointer return bool 的 check
          • 降低不必要的 compare
        • Reference: Checking for null pointer in c
    • Memory leak
      • C++ 引入了 unique_ptr, shared_ptr, weak_ptr 等smart pointers
        • Auto release resource at desstructor

沒有留言:

張貼留言