How malloc allocates memory and what is the size of Heap?
I don't understand the program which is shown below.
#include<stdio.h>
#include<sys/types.h>
#include<malloc.h>
main()
{
int *i1, *i2;
char *s;
printf("sbrk(0) before malloc(4): 0x%xn", sbrk(0));
i1 = (int *) malloc(4);
printf("sbrk(0) after `i1 = (int *) malloc(4)': 0x%xn", sbrk(0));
i2 = (int *) malloc(4);
printf("sbrk(0) after `i2 = (int *) malloc(4)': 0x%xn", sbrk(0));
printf("i1 = %p, i2 = %pn", i1, i2);
}
Output:
mohanraj@ltsp63:~/Development/chap8$ ./a.out
sbrk(0) before malloc(4): 0x8999000
sbrk(0) after `i1 = (int *) malloc(4)': 0x89ba000
sbrk(0) after `i2 = (int *) malloc(4)': 0x89ba000
i1 = 0x8999008, i2 = 0x8999018
mohanraj@ltsp63:~/Development/chap8$
The above output shows that, at the first time, the program break is 0x8999000. Once, the malloc is called, the program break is changed to 0x89ba000.
What is unclear to me:
What is the use of malloc. As per the reference, malloc is used to allocate memory in heap. At the initial stage of the program in execution, what is the size of the heap memory? At that time does the heap have memory or not. From the output, If the heap already have the memory, then why the program break is changed. The malloc automatically allocates the requested size of memory in heap.
From the above output, Once the malloc is called, the program break is changed. After the second time of the malloc called, the program break does not changed. So, it shows that at the initial stage of the execution of the program, the heap does not contain memory. Once the malloc is called then only the heap memory is allocated with the use of sbrk function. Is it right?
The heap grows automatically as you call malloc. Because sbrk calls are expensive, the system memory manager allocates big chunks of system memory, and then gives smaller pieces to the application. You are only allocating 4 bytes, when the heaps grows by over 128 k. Try allocating much more than 4 bytes, say 1 MB, and see what happens.
链接地址: http://www.djcxy.com/p/2478.html上一篇: 我如何写一个正确的微观