Page 1 of 1

memory management for local variables

Posted: Tue Mar 27, 2012 6:26 am
by compro
can anyone tell me how memory is allocated to variables declared in function(local variables)
lets say i have a kernel. now i know that dynamic allocation would start at the end of the kernel.
but where in memory are local variables stored??
i tried to figure out experimantally and what i found that local variables were give address<end of kernel
also with each new variable the address given was smaller than the last one.
is memory given to local variables from one of the following sections declared in link file(the text, bss, code section).
and also since memory address given to local variables is downwards(or in decreasing order) . is there any way to increase the space for local variables.

also once the function is returned will the memory address given to new local variables replace the ones that were already allocated the previous local variables or it will just keep going downwards.

Re: memory management for local variables

Posted: Tue Mar 27, 2012 6:33 am
by Solar
Local variables are placed on the stack. Stack space is not included in an executable, but set up by the kernel at runtime (setting the stack segment register).

Take note that your question hints at a certain lack of knowledge about details of how computer programs work that is excusable in userspace application programming, but usually a showstopper for most kernel-space work. This is not a field where "training on the job" tactics are encouraged.

Re: memory management for local variables

Posted: Tue Mar 27, 2012 6:34 am
by invalid
It depends on the language/compiler used. C typically reserves space for local variables on the stack. In assembler, AFAIK, you need to manage symbols manually, and if you want to reuse the space, you need to do so explicitly. What are you trying to achieve?

Re: memory management for local variables

Posted: Tue Mar 27, 2012 7:35 am
by compro
first of all i am no pro but just a student
also what i am trying to achieve is this

i have a kernel(a very basic one indeed)
i have set up the gdt
it is a flat memory model.
the stack segment has the same address as the data segment selector.
now i am not using any application on top of this kernel
i was just trying to see how local variables(declared in the main file of the kernel) are allocated space.

Re: memory management for local variables

Posted: Tue Mar 27, 2012 10:37 am
by Snake
How the local variables are allocated is determined by the compiler. They would be allocated to either the stack or the registers, depending on which optimizations your compiler uses. You might want to look at the C calling convention to see why and how the stack is used to implement functions. http://en.wikibooks.org/wiki/X86_Disass ... onventions