I am working an OS program and I am trying to figure out how malloc works pertaining to the stack. When a user calls malloc, is the pointer returned from malloc at the top of the stack and after the given space or at the bottom of the given space?
If I am loading variables into this new space using assembly code, and it isn’t enough to fill the whole space, should the variables be pushed in at the beginning of the freed space, or pushed to the point where the last variable would take up the last amount of free space given from malloc?
Thanks.
The whole point of
mallocis to not allocate from the stack, but from the heap. If you want to allocate from the stack, you’d usealloca.If you allocate on the stack and leave your current stack frame (that is, you return from the function) then the previously stack-allocated stuff might (in most situations: will) be overwritten by a different function call later on. So this obviously is not the place for “long-term” storage. For data that need to live longer than a function call, you need to allocate from the heap. That’s what
mallocdoes.How
mallocis doing its work depends on the OS features available and the implementation. See the question: How do malloc() and free() work?.