malloc(0)

来源:互联网 发布:js 双向绑定 编辑:程序博客网 时间:2024/05/16 15:03

先不费口舌了,看代码和运行结果吧:

#include <stdio.h>#include <string.h>#include <stdlib.h>int main(){        char* p = NULL;        p = malloc(0);        if(NULL == p)        {                printf("get a invalid point!\n");                return -1;        }        strcpy(p,"hello,world");        printf("len:%d,content:%s\n",strlen(p),p);                if(p)                free(p);        return 0;}


[xpple@localhost work]$  ./a.out
len:11,content:hello,world


malloc(0),能正常使用,而且不管多少个字符都能容纳得下。

在strcpy()时还显得更加明智,事先不需要根据源地址的字节大小来动态地申请空间。