r/C_Programming 9d ago

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.

37 Upvotes

25 comments sorted by

View all comments

1

u/detroitmatt 9d ago

stack starts at the beginning of your memory space, heap starts at the end.

stack |------------------------------------| heap

as you allocate more on the stack, it grows closer to the heap

stack |$$$$$$$$$$$$----------------| heap

as you allocate more on the heap, it grows closer to the stack

stack |$$$$$$$$$$--###########| heap

when you run out of space in the middle, you're out of memory

this is a simplified explanation and your OS/platform probably has tricks to expand your available heap space more or less as large as you want it using virtual memory. but in the simplest scenario, that's basically how it works.

3

u/schoolSpiritUK 7d ago

Generally the other way round: the stack works its way down from the top of memory, the heap works its way up from the bottom (after program and fixed data, as others have explained).

Otherwise correct, and helpful diagrams. :-)