转载地址:http://blog.csdn.net/bigheaven/article/details/7286862
感谢作者.
如下:
- #include<stdio.h>
- #include<string.h>
- #include<malloc.h>
- void main()
- {
- char *str = NULL;
- UpperCase(str);
- int *temp;
- if((temp = (int *)malloc(0)) == NULL)
- {
- printf("got a NULL pointer");//返回NULL指针
- }
- else
- {
- printf("got a valid pointer");//返回有效的指针 }
- printf("%d",sizeof(temp));//4,这只是指针占用内存
- }
解释:
首先:
在标准的malloc实现中,并不检查输入值的大小,而是将输入值做对齐操作后直接从堆上分配空间。
其次:
不论输入值的大小为多少,在malloc的内部最小的内存分配大小是一个定值(一般是8B),因为malloc需要用这部分空间来维护堆上的内存块链表。所以当用户申请一块0B的空间时,malloc实际分配的空间是8B,如果用户申请的空间是X,则malloc实际分配的空间是(对齐(X) + 8)。这也是为什么malloc分配的空间千万不能越界使用的原因:堆的内部链表结构将被破坏。
另外对于new和delete malloc和free这样的内存分配与释放函数:到底delete和free是怎么知道要释放掉多少内存的呢?
其实在new和malloc内存分配成功时,系统出除了返回一个指向这块内存的指针外,还会获得一块用于记录此处分配的内存大小的内存块:
- dlmalloc里面的解释:
- 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.
- If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item.
- dlmalloc里面的解释:
- 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.