r/C_Programming • u/Fuzzy_Recipe_9920 • Jul 24 '26
Where do stack and heap start
I apologise in advance for a dumb question and I will try to put it the way i could and I am sorry for that.
I know i chould chatgpt it, but learning from people helps me the best.
want to know how the memory is actually managed. I know it is managed by the kernel using different abstractions like virtual memory and paging.
My question arises when i think that each process that its own address space consisting stack frame, heap, globals vars etc.
But where do they even start? Kernel itself is a process so it must be having its own stack frame. Considering other programs need address space which is managed by kernel, like how does that work? Until Os is loaded, does stack and heaps exist even before that? Are they written in assembly?
I am sorry. I hope someone will be able to answer and i will be really glad if you could figure out what i am thinking wrong and missing.
View all comments
Show parent comment
6
u/lovelacedeconstruct Jul 24 '26
yup , the compiler produces object files with sections like
.text(for code).data(for global initialized variables).bss(for global uninitialized variables and they get zeroed out) and so on they have no notion of where in physical memory they will end up so you have to give them a map called a linker script that basically tells the linker how to fit them into actual address rangesYou need to basically using those abstract ideas to tell the linker which memory regions exist what are their sizes and which section goes where you could go crazy and no one stops you
you nedd to set the stack pointer so that when you allocate from the stack you know where to start, you need to tell malloc here is the region when someone asks you to allocate start from here
here is an example from a mircocontroller
you basically create a section in your memory
mark a spot as
_endwhich the standard library require for start address to allocating memory you basically say when malloc needs memory claim it starting from here (commonly known as heap start)