Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

    strace ls
    execve("/usr/bin/ls", ["ls"], 0x7ffd86646d90 /* 61 vars */) = 0
    brk(NULL)                               = 0x5581b6542000
I see brk(), that's glibc.


Does malloc() use brk() or mmap()?

https://stackoverflow.com/questions/30542428/does-malloc-use...

    there is a mallopt named M_MMAP_THRESHOLD, in general:
    
    If requested memory is less than it, brk() will be used;
    If requested memory is larger than or equals to it, mmap() will be used;


This is linux-specific though. Non-glibc mallocs have different tuning and many have completely foresworn brk/sbrk (openbsd and dragonflybsd mallocs haven't used brk in more than a decade[0]). In fact brk/sbrk is deprecated in every BSD:

On OpenBSD, DragonflyBSD, NetBSD and OSX:

> The brk and sbrk functions are historical curiosities left over from earlier days before the advent of virtual memory management.

On FreeBSD:

> The brk() and sbrk() functions are legacy interfaces from before the advent of modern virtual memory management. They are deprecated and not present on the arm64 or riscv architectures.

It's also somewhat discouraged on Solaris:

> The behavior of brk() and sbrk() is unspecified if an application also uses any other memory functions (such as malloc(3C), mmap(2), free(3C)).

[0] https://bugs.dragonflybsd.org/issues/84


Depends on system. In FreeBSD brk() syscall doesn’t even exist on newer platforms, such as RISC-V or aarch64.


In OpenBSD, brk/sbrk still exist but they removed its use from malloc something like 15 years ago.


If you go into the kernel, it's implemented in terms of mmap/munmap.


If you go into the kernel, all this is implemneted with page tables and MMUs.


You said there was no sbrk syscall, and there is.


brk() is undefined behavior if mmap is ever called.


I was wrong, it's only if you use MAP_FIXED to map an overlapping area.


How so? Both syscalls are invoked pretty frequently together in the same program.


Wow that's news to me - can you point me at the documentation for that?


Can you post a definite source supporting this?


There isn't one, because it's wrong.

Source: run strace on almost any useful Linux command (e.g. ls, sort, which, ...), you'll see it makes calls to both brk() and mmap().


The OP admitted it was wrong, but just because everyone does it doesn't mean it's not undefined behavior.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: