就像我在http://www.cnblogs.com/wuyuegb2312/p/3219659.html 文章中评论的那样,我也碰到了被提问这个malloc(0)的返回值问题,虽然感觉这样做在实际中没有任何意义,但既然被提问到了,那总得给点答复。当时的回答是“返回一个NULL指针”。

就像@五岳查看man结果的一样,我也查看了,malloc() allocates size bytes and returns a pointer to the allocated memory. The memory is not cleared. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().这句话翻译起来,就是传个0的话,返回值要么是NULL,要么是一个可以被free调用的唯一的指针。那是不是这篇文章中说的,通过这句话“

if(int pp = (strlen(ptr=(char *)malloc(0))) == 0)

”来判断是不是NULL指针呢?当然,实际情况到底如何,还得看代码。

刚看到@garbageMan一篇文章 http://www.cnblogs.com/pmer/p/3222648.html 这样写道:“malloc(0)唯一不同的地方就是,就算你申请内存成功,即malloc(0)返回值不为NULL,你也没法使用这块内存。”那到底是不是就没法使用呢?

我的测试代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h> int alloc_memory(char *p , int size)
{
printf("\nbefore malloc %p\n",p);
p = (char *)malloc(size);
if(!p)
{
printf("malloc error \n");
return -;
} //len of malloc(0)
printf("len of malloc(%d) is %d ,the ture is %d\n",size,strlen(p),malloc_usable_size(p)); //the first member
printf("the first member of malloc(%d) is %p:%d \n",size,p,*p); //set the first member
*p = ;
printf("set the first member of malloc(%d) is %p:%d \n",size,p,*p); //memcpy
memset(p,'\0',);
memcpy(p,"",);
printf("after memcpy , the content is %s len is %d , the ture is %d \n",p,strlen(p),malloc_usable_size(p)); free(p);
p = NULL; printf("\n");
} int main(int argc ,char **argv)
{
int size = -; char *p = NULL; //malloc(0)
size = ;
alloc_memory(p,size); //malloc(5)
size = ;
alloc_memory(p,size); //malloc(20)
size = ;
alloc_memory(p,size);
return ;
}

测试结果如下:

tiger@ubuntu:/mnt/hgfs/e/Lessons/MyExercise/UtilLibs/EXERCISE$ gcc -o malloc malloc.c
tiger@ubuntu:/mnt/hgfs/e/Lessons/MyExercise/UtilLibs/EXERCISE$ ./malloc before malloc (nil)
len of malloc() is ,the ture is
the first member of malloc() is 0x9e78008:
set the first member of malloc() is 0x9e78008:
after memcpy , the content is 012345678901len is , the ture is before malloc (nil)
len of malloc() is ,the ture is
the first member of malloc() is 0x9e78008:
set the first member of malloc() is 0x9e78008:
after memcpy , the content is 012345678901len is , the ture is before malloc (nil)
len of malloc() is ,the ture is
the first member of malloc() is 0x9e78018:
set the first member of malloc() is 0x9e78018:
after memcpy , the content is len is , the ture is tiger@ubuntu:/mnt/hgfs/e/Lessons/MyExercise/UtilLibs/EXERCISE$

从测试结果来看,可以得出以下几个结论:

1. malloc(0)在我的系统里是可以正常返回一个非NULL值的。这个从申请前打印的before malloc (nil)和申请后的地址0x9e78008可以看出来,返回了一个正常的地址。

2. malloc(0)申请的空间到底有多大不是用strlen或者sizeof来看的,而是通过malloc_usable_size这个函数来看的。---当然这个函数并不能完全正确的反映出申请内存的范围。

3. malloc(0)申请的空间长度不是0,在我的系统里它是12,也就是你使用malloc申请内存空间的话,正常情况下系统会返回给你一个至少12B的空间。这个可以从malloc(0)和malloc(5)的返回值都是12,而malloc(20)的返回值是20得到。---其实,如果你真的调用了这个程序的话,会发现,这个12确实是”至少12“的。

4. malloc(0)申请的空间是可以被使用的。这个可以从*p = 10;及memcpy(p,"01234567890123456789",12);可以得出。

虽然malloc(0)没有发现在现实中有什么意义,但是既然有些人非要我们回答,那我们还是有必要探究一下的,否则你只有被pass掉了。关于这个问题的讨论很值得,因为它让我对技术更加感兴趣,不经意间学到了其他的知识。

如果大家有什么不同意见,欢迎跟帖讨论,谢谢!

注:---后为新增内容。


总结:为了安全起见,malloc(0)的非NULL返回值,最好不要进行除了free()之外的任何操作!

关于内存管理方面,大家可以参考IBM上的一篇文章:http://www.ibm.com/developerworks/cn/linux/l-memory/

非常感谢garbageMan playerc 求道于盲 五岳 懒得想一个好名字 等同仁的参与教导,小弟12年自动化专业刚毕业,知识面尚浅薄,以后有什么问题,还望博客园的各位不吝赐教,谢谢!

关于malloc(0)的返回值问题--这两天的总结与实践篇的更多相关文章

  1. DWR3.0 dwr 返回值(数组,集合,Map)

    首先导入项目所需要的包,如下:dwr.jar,commons-logging-1.0.4.jar,版本可以调整 1.web.xml<?xml version="1.0" en ...

  2. C语言中malloc函数返回值是否需要类型强制转换问题

    1. 在C语言中, 如果调用的函数没有函数原型, 则其返回值将默认为 int 型. 考虑调用malloc函数时忘记了 #include <stdlib.h>的情况 此时malloc函数返回 ...

  3. libusb_bulk_transfer返回值不是0

    libusb_bulk_transfer返回值不是0 libusb_bulk_transfer返回值不是0libusb_bulk_transfer返回值不是0 ?????

  4. malloc(0)分配多少内存?(译文)

    原文地址:http://prog21.dadgum.com/179.html 在大多的系统中,这个C的小程序将会吸收全部空闲的内存. ){ ); } 在我们聊malloc(0)之前,让我们看看mall ...

  5. 【Go入门教程3】流程(if、goto、for、switch)和函数(多个返回值、变参、传值与传指针、defer、函数作为值/类型、Panic和Recover、main函数和init函数、import)

    这小节我们要介绍Go里面的流程控制以及函数操作. 流程控制 流程控制在编程语言中是最伟大的发明了,因为有了它,你可以通过很简单的流程描述来表达很复杂的逻辑.Go中流程控制分三大类:条件判断,循环控制和 ...

  6. GetQueuedCompletionStatus的返回值

    完成端口GetQueuedCompletionStatus返回值的问题 先看看GetQueuedCompletionStatus函数的完整声明:BOOL GetQueuedCompletionStat ...

  7. ADO.NET笔记——使用Command执行增删改操作,通过判断ExecuteNonQuery()返回值检查是否操作成功

    相关知识: ExecuteNonQuery()方法:执行CommandText属性所制定的操作,返回受影响的记录条数.该方法一般用来执行SQL中的UPDATE.INSERT和DELETE等操作 对于U ...

  8. C++11获取线程的返回值

    C++11 std::future and std::promise 在许多时候,我们会有这样的需求--即我们想要得到线程返回的值. 但是在C++11 多线程中我们注意到,std::thread对象会 ...

  9. python入门(14)定义函数和接收返回值

    定义函数: 定义一个求绝对值的my_abs函数为例: def my_abs(x): if x >= 0: return x else: return -x 如果没有return语句,函数执行完毕 ...

随机推荐

  1. utf8_unicode_ci、utf8_general_ci区别

    摘录一下Mysql 5.1中文手册中关于utf8_unicode_ci与utf8_general_ci的说明:   当前,utf8_unicode_ci校对规则仅部分支持Unicode校对规则算法.一 ...

  2. (转)TP-LINK WR720N v3 刷OpenWrt

    之前买了一台改过硬件的TP-Link WR841N-V7路由器,并且成功刷机OpenWrt也完成了FQ,WR841N-V7的更多详情可以看这里,但是可能卖家焊接的有问题,导致老是听到滋滋滋高频率的赤耳 ...

  3. ZooKeeper的安装和API

    Zookeeper的分布式安装和API介绍: 安装教程 在datanode1.datanode2和datanode3三个节点上部署Zookeeper. 步骤 解压zookeeper安装包到/opt/m ...

  4. datagrid行内编辑时为datetimebox

    $.extend($.fn.datagrid.defaults.editors, { datetimebox: {// datetimebox就是你要自定义editor的名称 init: functi ...

  5. 数组转换成json key-value形式

    eg1(数组中包含的是数组): var jsonData = {}; var arr = [[1, 'boy', 'dabing'], [2, 'girl', 'dabing']]; for (var ...

  6. day2作业(基本数据类型,语法)

    #coding:utf-8 '''1.写代码实现用户输入用户名和密码,当用户名为 seven 且 密码为 123 时,显示登陆成功,否则登陆失败!实现用户输入用户名和密码,当用户名为 seven 且 ...

  7. 十年阿里java架构师的六大设计原则和项目经验

      先看一幅图吧: 这幅图清晰地表达了六大设计原则,但仅限于它们叫什么名字而已,它们具体是什么意思呢?下面我将从原文.译文.理解.应用,这四个方面分别进行阐述. 1.单一职责原则(Single Res ...

  8. java的list遍历

    for(String str : list) {//增强for循环,其内部实质上还是调用了迭代器遍历方式,这种循环方式还有其他限制,不建议使用. System.out.println(str); } ...

  9. 接口详解例子代码(附Java1.8的接口新特性)

    接口,与抽象类类似但是区别也很大,他们都是标签,用来提醒父类一定要实现的类里创建抽象方法.而接口类可以implements 多个接口,抽象类则只能父类只能继承一个抽象类,与抽象不同的是它不是继承组合关 ...

  10. mysql大纲

    一.概述 1.1 关系型数据.非关系型数据.半关系型数据 1.2 关系型数据库和非关系型数据库 1.3 发展史 二.MySQL组件和安装 三.数据库语言和主要概念 3.1 数据库语言 DML.DDL. ...