C语言 malloc(0)的问题

2 篇文章 0 订阅

转载地址:http://blog.csdn.net/bigheaven/article/details/7286862

感谢作者.


如下:

[cpp]  view plain copy
  1. #include<stdio.h>  
  2. #include<string.h>  
  3. #include<malloc.h>  
  4.   
  5. void main()  
  6. {  
  7.     char *str = NULL;  
  8.     UpperCase(str);  
  9.   
  10.     int *temp;  
  11.     if((temp = (int *)malloc(0)) == NULL)  
  12.     {  
  13.         printf("got a NULL pointer");//返回NULL指针  
  14.     }  
  15.     else   
  16.     {  
  17.         printf("got a valid pointer");//返回有效的指针 }  
  18.     printf("%d",sizeof(temp));//4,这只是指针占用内存  
  19. }  


 解释:

首先: 
    在标准的malloc实现中,并不检查输入值的大小,而是将输入值做对齐操作后直接从堆上分配空间。 
其次: 
    不论输入值的大小为多少,在malloc的内部最小的内存分配大小是一个定值(一般是8B),因为malloc需要用这部分空间来维护堆上的内存块链表。所以当用户申请一块0B的空间时,malloc实际分配的空间是8B,如果用户申请的空间是X,则malloc实际分配的空间是(对齐(X)   +   8)。这也是为什么malloc分配的空间千万不能越界使用的原因:堆的内部链表结构将被破坏。

另外对于new和delete malloc和free这样的内存分配与释放函数:到底delete和free是怎么知道要释放掉多少内存的呢?

其实在new和malloc内存分配成功时,系统出除了返回一个指向这块内存的指针外,还会获得一块用于记录此处分配的内存大小的内存块:

[css]  view plain copy
  1. dlmalloc里面的解释:  
  2. If n is zero, malloc returns a minimum-sized chunk. (The minimum size is 16 bytes on most 32bit systems, and 32 bytes on 64bit systems.)  Note that size_t is an unsigned type, so calls with arguments that would be negative if signed are interpreted as requests for huge amounts of space, which will often fail. The maximum supported value of n differs across systems, but is in all cases less than the maximum representable value of a size_t.  

 

[css]  view plain copy
  1. If   size   is   0,   malloc   allocates   a   zero-length   item   in   the   heap   and   returns   a   valid   pointer   to   that   item.  

[css]  view plain copy
  1. dlmalloc里面的解释:  
  2. If n is zero, malloc returns a minimum-sized chunk. (The minimum size is 16 bytes on most 32bit systems, and 32 bytes on 64bit systems.)  Note that size_t is an unsigned type, so calls with arguments that would be negative if signed are interpreted as requests for huge amounts of space, which will often fail. The maximum supported value of n differs across systems, but is in all cases less than the maximum representable value of a size_t.  


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值