In the sbrk(2) manual,
it states that
Calling
sbrk()with an increment of 0 can be used to find the current location of the program break.
How does this work when sbrk(0) is used to initialize a static variable?
Say,
static void* current_heap = sbrk(0);
This curiosity stems from the typical compilation steps of C/C++ code determine the size of the data segment at compile time.
As shown in the diagram below,
Distributed under CC BY-SA 3.0
the initialized static variables are stored in the data segment. And as far as I know, the heap normally starts from the end of BSS and data segments.
How does sbrk(0) know where heap starts during compilation while other static variables might not have been determined?
UPDATE:
As noted by @EugeneSh, here's a working example compiled with clang++:
#include <unistd.h>
#include <iostream>
static void* current_heap = sbrk(0);
int main() {
std::cout << current_heap << '\n';
}
