What's the point of malloc(0)?

后端 未结 17 1779
庸人自扰
庸人自扰 2020-11-22 15:40

I just saw this code:

artist = (char *) malloc(0);

...and I was wondering why would one do this?

17条回答
  •  臣服心动
    2020-11-22 15:48

    Here is the analysis after running with valgrind memory check tool.

    ==16740== Command: ./malloc0
    ==16740==
    p1 = 0x5204040
    ==16740==
    ==16740== HEAP SUMMARY:
    ==16740==     in use at exit: 0 bytes in 0 blocks
    ==16740==   total heap usage: 2 allocs, 2 frees, 1,024 bytes allocated
    ==16740==
    ==16740== All heap blocks were freed -- no leaks are possible
    

    and here's my sample code:

    #include 
    #include 
    #include 
    
    int main()
    {
       //int i;
       char *p1;
    
       p1 = (char *)malloc(0);
       printf("p1 = %p\n", p1);
    
       free(p1);
    
       return 0;
    
    }
    

    By default 1024 bytes is allocated. If I increase the size of malloc, the allocated bytes will increase by 1025 and so on.

提交回复
热议问题