次のコードを使用します。
int *p = malloc(2 * sizeof *p);
p[0] = 10; //Using the two spaces I
p[1] = 20; //allocated with malloc before.
p[2] = 30; //Using another space that I didn't allocate for.
printf("%d", *(p+1)); //Correctly prints 20
printf("%d", *(p+2)); //Also, correctly prints 30
//although I didn't allocate space for it
この行malloc(2 * sizeof *p)
で、2 つの整数にスペースを割り当てていますよね?しかし、3 番目の位置に を追加しint
ても、正しく割り当てられ、取得可能になります。
私の質問は、なぜ使用時にサイズを指定するのmalloc
ですか?