0
int main(int argc, char ** argv)
{
 char *p[10];
 
 for(int i =0 ; i < 10; ++i)
 {
 ssize_t msize = pow(2,i) * sizeof(char);
 p[i] = (char*)malloc(msize);
 printf("%p\n",sbrk(0));
 }
 printf("malloc done!\n");
 
 for(int i =0 ;i < 10; ++i)
 {
 free(p[i]);
 }
 exit(0);
}

The output like that:

0x55ffd4dd5000
0x55ffd4dd5000
0x55ffd4dd5000
0x55ffd4dd5000
0x55ffd4dd5000
0x55ffd4dd5000
0x55ffd4dd5000
0x55ffd4dd5000
0x55ffd4dd5000
0x55ffd4dd5000
malloc done!

When using malloc() to allocate the blocks of memory smaller than MMAP_THRESHOLD bytes, the glibc malloc() will use sbrk() or brk() to finish that. As known, both brk() and sbrk() will adjust the size of the heap.

So if I use malloc() to allocate the small(size < MMAP_THRESHOLD) memory block, the heap should be changed, But why does heap not change in this case?

asked Aug 5, 2022 at 6:47
4
  • 1
    If you want to add information to the question, then please edit the question. Please don't use comments for this, as comments should only be used to respond to other people's comments. Commented Aug 5, 2022 at 6:50
  • 2
    Please edit your question to explain why you think successive calls to sbrk(0) should return different values. Commented Aug 5, 2022 at 6:52
  • 1
    "Why does "the program break" not change". malloc implementations typically have a cache of blocks. It does not need to increase the heap for every malloc call. Commented Aug 5, 2022 at 6:56
  • most malloc implementations these days use mmap to get memory from the system, rather than brk/sbrk Commented Aug 5, 2022 at 7:18

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.