Runtime Memory allocation on stack

c

Solution

In short they usually don't use system calls, unless running out of available memory.

The bahavior is different for either, so I explain differently.

malloc

Let's say initially your program has 1MB (for example) available memory for allocation. `malloc` is a (standard) library function that takes this 1MB, looks at the memory you want to allocate, cut a part of the 1MB out and give it to you. For book-keeping, it keeps a linked-list of unallocated memories. The `free` function then adds the block being freed back to the free list, effectively freeing the memory (even though the OS still doesn't get any of it back, unless `free` decides that you have way too much memory and actually give it back to the OS).

Only when you run out of your 1MB does `malloc` actually ask the operating system for more memory. The system call itself is platform dependent. You can take a look at this answer for example.

alloca

This is not a standard function, and it could be implemented in various ways, none of which probably ever call any system functions (unless they are nice enough to increase your stack size, but you never know).

What `alloca` does (or equivalently the (C99) standard variable length arrays (VLA) do) is to increase the stack frame of the current function by adjusting proper registers (for example `esp` in x86). Any variable that happens to be on the same stack frame but located after the variable length array (or `alloca`ed memory) would then be addressed by `ebp + size_of_vla + constant` instead of the good old simple `ebp + constant`.

Since the stack pointer is recovered to the frame of the previous function upon function return (or generally on exit of any `{}` block), any stack memory `alloca`ted would be automatically released.

Problem

I want to know about runtime memory allocation on stack area and how its different from runtime memory allocation on Heap area. I know how memory get allocated by using library function. ``` #include<alloca.h> void *alloca(size_t size); //(for runtime memory on stack) #include<stdlib.h> void *malloc(size_t size); //(for run time memory on heap) ``` I also know that if we are using alloca function we don't need to free that memory explicitly because it is associated with stack, its get freed automatically. I want to know which system calls are associated with alloc and malloc and how they works in both.

Original source

Related problems