How/where is sbrk used within malloc.c?
Asked Answered
G

1

7

I have read in Advanced Unix Programming (and also in a few other books) that Linux malloc() uses the Linux system call sbrk() to request memory from the operating system.

I am looking at the glibc malloc.c code and I can see many mentions of sbrk() in the comments, but not referred to directly in the code.

How/where is sbrk() referred to/used when malloc() requests memory from the OS?

(This could be a general misunderstanding on my part of how system calls are made from the C runtime library. If so, I would be interested to know how they are made??)

Girth answered 31/12, 2013 at 21:22 Comment(4)
While I'm not sure about the actual location of sbrk, there's nothing different between a system call in C and a function, with the exception that control is completely managed by the operating system until the system call completes.Hemstitch
sbrk(2) tend to become rusty and obsolete. There are good reasons (multi-threading) to use mmap(2) only.Sheelah
@BasileStarynkevitch could you briefly elaborate on such reasons?Girth
Read the man page. sbrk is removed from latest Posix standard.Sheelah
D
9

Glibc's malloc.c requests more memory by calling the function stored in the __morecore global function pointer (the call actually uses the macro MORECORE which expands to __morecore). By default, this holds the address of function __default_morecore, which is defined in morecore.c. This function calls sbrk.

Note that some malloc implementations may use mmap to get more memory instead of sbrk.

Doubletongue answered 31/12, 2013 at 21:39 Comment(4)
Cool- have found it. The comment in morecore.c says: "Allocate INCREMENT more bytes of data space, and return the start of data space". So if I want 100 bytes of data I call malloc() which ends up calling the function in morecore.c, which calls sbrk() and this function returns a pointer to the beginning of the 100 bytes? Or does sbrk() get used before main() is called to allocate the whole heap for the process?Girth
@Girth The heap size is not known in advance, so sbrk will be called by malloc. But it won't translate 1 to 1, because malloc will probably request larger blocks of memory from sbrk and then divide them, and it can also return previously freed memory to the caller without needing sbrk.Doubletongue
So all sbrk does is to accept a request for memory, given a size and provide a pointer to it. Isnt this VERY similar to what malloc does()? In other words, what is the purpose of malloc() if sbrk does this? Just to put a load of error-handling in?Girth
sbrk() doesn't know which parts of the memory are still in use, as there's no equivalent to free; malloc handles recycling of memory blocks that have been malloc()ed and free()d.Isobar

© 2022 - 2024 — McMap. All rights reserved.