动态内存分配一题

下面代码片断的输出是什么,为什么?

char *ptr;

if ((ptr = (char *)malloc(0)) == NULL) 
{
      puts("Got a null pointer.");
}
else
{
      puts("Got a valid pointer.");
}

 

析:
通过查看 malloc 的手册如下:
The malloc() function allocates size bytes and returns a pointer to the allocated memory.  The memory is not initialized.  If size is  0,  then malloc()  returns either NULL, or a unique pointer value that can later be successfully passed to free().

malloc申请的是一块未初始化的内存空间,如果传如的值为0,可能返回NULL,或者是一个特殊的指针值以用于free函数。

实际测试时,输出的是 Got a valid pointer.
也就是说未返回NULL。但这本身是一个不正确的判断方法。

posted @ 2015-03-05 17:01  阿青1987  阅读(131)  评论(0编辑  收藏  举报