malloc(0)

来源:互联网 发布:刷话题软件 编辑:程序博客网 时间:2024/05/17 15:20

最近,看了有关malloc(0)的返回值以及其他一些问题的讨论,我把自己的感受和看法记录如下:

问题:

char* ptr = malloc(0*sizeof(char));if(NULL == ptr) {    printf("got a NULL pointer");} else {    printf("got a Valid pointer");}

  通过查看malloc的man手册:The malloc() function allocates size bytes and returns a pointer to the allo‐cated 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().这句话翻译起来,就是传个0的话,返回值要么是NULL,要么是一个可以被free调用的唯一的指针。
  通过下面代码来测试:

#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 -1;    }    printf("len of malloc(%d) is %lu,the ture is %lu\n", size, strlen(p), malloc_usable_size(p));    printf("the first member of malloc(%d) is %p : %d \n", size, p, *p);    *p = 10;    printf("set the first member of malloc(%d) is %p : %d \n", size, p, *p);    memset(p, '\0', 24);    memcpy(p, "012345678901234567891235", 23);    printf("after memcpy, the content is %s len is %lu, the ture is %lu\n", p, strlen(p), malloc_usable_size(p));    free(p);    p = NULL;    printf("\n");}int main(int argc ,char **argv){    int size = -1;    char *p = NULL;    size = 0;    alloc_memory(p,size);    size = 5;    alloc_memory(p,size);    size = 40;    alloc_memory(p,size);    return 0;}

上述代码用gcc 4.8.4编译运行结果如下:

zxd@xlg:~/c++$ gcc test.czxd@xlg:~/c++$ ./a.out before malloc (nil)len of malloc(0) is 0,the ture is 24the first member of malloc(0) is 0x22fc010 : 0 set the first member of malloc(0) is 0x22fc010 : 10 after memcpy, the content is 01234567890123456789123 len is 23, the ture is 24before malloc (nil)len of malloc(5) is 0,the ture is 24the first member of malloc(5) is 0x22fc010 : 0 set the first member of malloc(5) is 0x22fc010 : 10 after memcpy, the content is 01234567890123456789123 len is 23, the ture is 24before malloc (nil)len of malloc(40) is 0,the ture is 40the first member of malloc(30) is 0x22fc030 : 0 set the first member of malloc(30) is 0x22fc030 : 10 after memcpy, the content is 01234567890123456789123 len is 23, the ture is 40

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

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

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

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

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