Re: Initializing arrays
小野@名古屋大学 です.
<YAS.04Jan20152946@kirk.is.tsukuba.ac.jp>の記事において
yas@is.tsukuba.ac.jpさんは書きました。
yas> >> char src[10]; のような配列の場合、未定義でアクセスしても、そ
yas> >> れだけでは決して bus error になったりはしません。単に前に使っ
yas> >> ていたメモリの内容が出てくるだけです。
yas> > a[10] という配列の場合, アドレスとしては a+0〜a+10 が, データとし
yas> > ては a[0]〜a[9] が有効であり, それ以外のアクセスについては
yas> > undefined behavior となっています. 従って
yas> > 現実的には:
yas> > bus error はないかもしれませんが segmentation fault はありえます.
yas> bus error と segmentation fault は、なにか違いがあるんですか。
意味は違うんじゃないですか?
yas> アドレスとして a[10] が有効というのは、なんか変です。規格に
yas> あるんですか。
規格を調べていただければよいのですが....
# 私は「アドレスとして a[10] が有効」とは書いていないです.
6.5.6 Additive operators, paragraph 8 から:
.... Moreover, if the expression P points to the last element of
an array object, the expression (P)+1 points one past the last
element of the array element, and if the expression Q points one
past the last element of the array object, the expression (Q)-1
points to the last element of the array object. If both the
pointer operand and the result point to elements of the same
array object, or one past the last element of the array object,
the eveluation shall not produce an overflow; otherwise, the
behabior is undefined. If the result points one past the last
element of the array object, it shall not be used as the operand
of a unary * operator that is evaluated.
大きさ 10 の配列 a に対して a+10 は one past the last element of
the array object を指すので合法的に使うことができる. a+11 は one
past the last element of the array object を指さないし element of
the same array object も指さないから undefined behavior.
もちろん a+10 は one past the last element of the array object を
指すので *(a+10) はやっちゃいけない (undefined behavior) だし, 等
価な a[10] も同じく undefined behavior.
yas> Subject: は、初期化しない配列を使うとどうなるかという話でし
yas> た。src[10] = "abc" で、src[5] を使うとどうなるかという話。
yas> もともとは。
こちらも 6.7.8 Initialization, paragraph 21 から:
If there are fewer initializers in a brace-enclosed list than
there are elements or members of an aggregate, or fewer
characters in a string literal used to initialize an array of
known size than there are elements in the array, the remainder of
the aggregate shall be initialized implicitly the same as objects
that have static storage duration.
つまり,
char src[10] = "abc";
だったら src[5] は 0 になります.
--
名古屋大学大学院 情報科学研究科 計算機数理科学専攻
小野 孝男
Fnews-brouse 1.9(20180406) -- by Mizuno, MWE <mwe@ccsf.jp>
GnuPG Key ID = ECC8A735
GnuPG Key fingerprint = 9BE6 B9E9 55A5 A499 CD51 946E 9BDC 7870 ECC8 A735