【发布时间】:2017-01-24 21:50:13
【问题描述】:
我最近对 C 中 malloc 函数的行为很感兴趣,并且我观察到了一个有趣的行为。看起来 malloc 为 NULL 后的第一个“越界”值(或至少返回被if 视为错误的东西)。
这是一个插图:
int main (){
int i;
double * d_ptr = malloc (10 * sizeof (double)); //malloc 10 double
for (i=0 ; i<10 ; i++){ // initialise them ...
d_ptr[i] = 42;
}
for (i=0 ;i <50 ; i++){ /// loop obviously trying to go out of bounds
if (d_ptr[i]){
printf("i=%d,d[%d]=%f\n",i,i,d_ptr[i]);
}
else {
printf("out of bounds : i=%d\n",i);
break;
}
}
printf("exited 'out of bounds loop' safely\n");
free(d_ptr);
return 0;
}
这是输出:
i=0,d[0]=42.000000
i=1,d[1]=42.000000
i=2,d[2]=42.000000
i=3,d[3]=42.000000
i=4,d[4]=42.000000
i=5,d[5]=42.000000
i=6,d[6]=42.000000
i=7,d[7]=42.000000
i=8,d[8]=42.000000
i=9,d[9]=42.000000
out of bounds : i=10
exited 'out of bounds loop' safely
我的问题是:
这种行为是否可以预测?我尝试了一堆变量类型,malloc 的不同大小,我总是安全地退出循环。
-
如果它是可预测的,它是否可以成为循环指针的可靠方法,在这种情况下知道它们的“大小”会很棘手,或者需要大量重写?
- 最后,更深层的解释是什么?做 malloc 在要求的内存空间后多分配一个字 分配?
【问题讨论】:
-
越界访问是未定义的行为。任何事情都有可能发生,这绝对是不可预测的。
-
在分配内存后尝试释放内存,然后分配一个稍小的块,看看在新块的末尾是否仍然得到
0。
标签: c pointers segmentation-fault malloc