考虑此代码:
main() {
float *ptr = NULL;
while(true) {
ptr = (float *)realloc(ptr, 0*sizeof(float));
fprintf(stdout,"Errno: %d, Ptr value: %d\n",errno, (int)ptr);
}
}
奇怪的是,从来没有设置errno(至少对我来说是这样),但是调用会返回NULL和指针值。我的想法是,0分配会返回某种错误,但不会严重到足以设置errno的程度。否则带有realloc的代码有问题。我不确定。
我不太在意,但这导致我(0字节)内存泄漏。
只需使用中间变量。例如
int main( void ) {
float *ptr = NULL;
while(true) {
float *tmp = realloc(ptr, 0*sizeof(float));
if ( !tmp )
{
// report an error
break;
}
ptr = tmp;
//...
}
}
对于零大小的内存请求,则根据C标准(7.22.3内存管理功能)
如果请求的空间大小为零,则行为为实现定义:返回空指针,或者返回行为就像大小是一些非零值,除了返回的指针不得用于访问对象。