変数が初期化されていない場合、if ステートメントは常に機能すると想定しても安全ですか? 仮定はイエスですが、変数内のゴミのランダムなビットは、null かどうかのチェックが機能することを常に意味するわけではないと言われています。
Void afunction () {
char* someStr;
if (someStr)
{
// do something
}
}
変数が初期化されていない場合、if ステートメントは常に機能すると想定しても安全ですか? 仮定はイエスですが、変数内のゴミのランダムなビットは、null かどうかのチェックが機能することを常に意味するわけではないと言われています。
Void afunction () {
char* someStr;
if (someStr)
{
// do something
}
}
Is it safe to assume that the if statement will always work if the variable is uninitialized?
No. Reading uninitialized storage invokes undefined behavior. You can't make safe assumptions about this code.
Don't do this!
This is absolutly not guaranteed to always work. You have to initialize it yourself.
char* someStr = NULL;
or some other value.
初期化されていない変数は不定です。値を割り当てる前にそれらを読み取ると、未定義の動作が発生します。
ポインタが次のようになっているかどうかを確認するのはとても簡単ですNULL
:
if (someStr) {
// Don't use it (or do for some weird reason)
}
安全のために、ポインタが希望する値であることを確認するには、初期化時に値を割り当てます。
char* someStr = NULL;
未定義の動作を回避するために、ポインターを静的にすることもできます。
static char* someStr;
The value of someStr
is not defined. In general it will be set to some old value lying around on the stack. So, it may well be NULL (that is, 0).