请看下面的代码:
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)
,我为两个整数分配了空间,对吗?但是如果我在第三个位置添加一个int
,它仍然可以正确分配和检索。
那么我的问题是:为什么在使用malloc
时要指定大小?