Posted on September 16th, 2007 at 21:51 by fr3@K
最近被我面試的十來位應徵者, 除了一位之外, 都不清楚以下兩個 pointer to NULL (指向 0 的指標) 的基本特性:
delete一個指向NULL的指標是安全的- 以一個指向
NULL的 C-style 字串為參數呼叫strlen會造成死機 (segmentation fault, access violation or whatever)
在公司標準的試卷上有一題是實作一個 string class, 包含
operator= 在內的幾個主要 member function:
class String
{
public:
// ...
String& operator=(const String& other);
private:
char* data_;
};
於是就常會在答案卷看到類似下面這樣, 有趣的 String::operator= 實作:
String& String::operator=(const String& other)
{
if(this == &other)
return *this;
if(data_ != NULL)
delete [] data_;
data_ = new char[strlen(other.data_) + 1];
strcpy(data_, other.data_);
return *this;
}
看似小心翼翼地在 delete 之前檢查 String::data_ 是否為 NULL (即便毫無意義), 卻又天真地完全不理會呼叫 strlen 時參數為 NULL 的後果.
![]() |
|
| Previous Post « WP-Notable - Patched to Support funP and HEMiDEMi « |
Next Post » 變更原代碼授權 » |








我還沒想過 strlen 給他一個 = NULL 的指標會當掉的問題ㄝ,
這不是 strlen 自己要去檢測的嗎。
這有是歷史的淵源嗎???
不然通常我自己寫的函式都會先來個 if( p == NULL) return; 這類的,
還是這樣是多餘是不好的行為呢??
還有~~你們應該是想看看有沒有人會提出用 \’0′ 結尾字串比較不好的論點吧。
Comment by 烤布雷 — September 18, 2007 @ 16:47