Malloc -> how much memory has been allocated?

后端 未结 7 1243
梦谈多话
梦谈多话 2020-12-20 18:44
# include 
# include 
# include 
# include 

int main ()
{
  char * buffer;
  buffer = malloc (2);

          


        
7条回答
  •  生来不讨喜
    2020-12-20 19:27

    Malloc -> how much memory has been allocated?

    When you allocate memory using malloc. On success it allocates memory and default allocation is 128k. first call to malloc gives you 128k.

    what you requested is buffer = malloc (2); Though you requested 2 bytes. It has allocated 128k.

    strcpy(buffer, "hello"); Allocated 128k chunk it started processing your request. "Hello" string can fit into this.

    This pgm will make you clear.

    int main()
    {
    int *p= (int *) malloc(2);---> request is only 2bytes
    
    p[0]=100;
    p[1]=200;
    p[2]=300;
    p[3]=400;
    p[4]=500;
    
    int i=0;
    

    for(;i<5;i++,p++)enter code here printf("%d\t",*p);

    }
    

    On first call to malloc. It allocates 128k---> from that it process your request (2 bytes). The string "hello" can fit into it. Again when second call to malloc it process your request from 128k.

    Beyond 128k it uses mmap interface. You can refer to man page of malloc.

提交回复
热议问题