LoginSignup
4
3

More than 5 years have passed since last update.

Is《0+(int*)malloc(1)》well defined in C99?

Last updated at Posted at 2015-11-20

知人から
http://twitter.com/mohitj83/status/667207656751263744

@Nabetani Referring 6.5.6/8 in C99 specs, After [int *p = malloc(1);] (Assume sizeof(int) > 1) succeeds, is [int *q = p+0;] well defined?

という質問を受けたので、答えを。

で。
C も C++ も、ポインタは

  • 有効なアドレス
  • 有効なアドレスの次のアドレス

のいずれかを指していなければならず、そうでない場合は未定義になる。
例えば

c99
int ary[2]={0}
int * p = ary; // well defined.
int * q = ary+1; // well defined.
int * r = ary+2; // well defined.
int * s = ary+3; // NOT well defined.

こんな具合。

というわけで、sizeof(int)==4 なら、

c99
int * p0 = malloc(4);
int * q0 = p0+0; // well defined.
int * r0 = p0+1; // well defined.
int * s0 = p0+2; // NOT well defined.

となる。
であれば。

c99
int * p1 = malloc(1); 
int * q1 = p1+0;

q1 は、r0 が well defined であるのと同じ理由で well defined となりそうな気もする。
が。
そもそも p1 が well defined ではないように思う。

malloc は「The pointer returned if the allocation
succeeds is suitably aligned」となっていて、引数が 1 の場合の「suitably aligned」が int に合っているとは限らないと思う。

というわけで、私の答えは
「q is not well defined because p is not well defined.」
になった。

全然自信がない。

どう思う?

4
3
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3