我知道函数brk(),sbrk()用于重新分配内存。但它们与realloc()函数有什么不同?。给我编码示例。
brk
and sbrk
are system calls (implemented in the kernel) while malloc
, free
, realloc
are library functions in user space. So the malloc
etc functions use brk
and sbrk
internally but provide additional functionality (see man(2) for more details about brk
and man(3) for more details about malloc
.).
brk
only tells the kernel how much memory your program wants to use, by giving the the kernel a pointer to the largest virtual memory location that your program may use. But you only have exactly one big chunk of memory.
malloc
helps you to subdivide this huge block of memory into smaller parts.
Example code doesn't make much sense here, because brk
and malloc
work on different levels. But you could think how you would implement a very simple (and non-thread-safe) version of malloc
and free
and where you would use brk
there:
brk
to increase the usable memory we got from the kernel And as @BasileStarynkevitch remarked in his comment, as an alternative to brk
you could also use mmap
(with fd=-1
and flags=MAP_PRIVATE|MAP_ANONYMOUS
) to reserve a single block of memory backed by the swap file. For details about mmap see man(2) .
At the OS level (in the Unix model, at least), your program has one big region of memory for program text, initialized and uninitialized data, and the "heap", for dynamically-allocated data. (The stack is separate.) You can adjust the size of that region using brk
and sbrk
, but you can't rearrange it, and it's always contiguous. The vast majority of programs that do dynamic memory allocation require something more flexible.
malloc
, free
, and realloc
are C library functions that give you something more flexible. Underneath, they get memory from the OS by calling brk
and/or sbrk
, but then they do extra processing to let you allocate (a) any number of chunks of (b) different sizes and which you can (c) individually return to the pool when you're done with them and incidentally (d) resize.
But when you return memory to the pool with free
, it generally just goes back into the pool that future calls to malloc
by your program will draw from; memory is generally not given back to the OS.
(Sorry for not providing any example code; I don't have time for that just now.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.