Wednesday, December 30, 2009

Complier Allocating the memory in different areas

Consider the following lines of code:

Question is where will these variables and constant be allocated in the micro controller?

static char x; /* Static uninitialized variable */
static char y = 10; /* Static initialized variable */
const char z = 20; /* Constant data */

void f1(void)
{
char a; /* goes into stack */
a = 1;

x = y + z;
}

Answer:

compiler will allocate 'x' to a location in RAM section.
compiler will allocate 'y' to a location in RAM as well as ROM.
compiler will allocate 'z' to a location in ROM
compiler will allocate 'a' will be allocated a space dynamically in the stack.

example:

let us say we have a 8 bit micro controller
char means 8 bits of memory

ROM size is 20 bytes (Address: 0x00 to 0x14)
RAM size is 10 bytes (Address: 0x15 to 0x1E)


So, initially one has to reserve memory for (limited types for simplicity)
a) Code - ROM - (0x00 to 0x10)
b) Constant Data - ROM - (0x11 to 0x12)
c) Initialized data - ROM - (0x13 to 0x14)
d) Initialized Variables - RAM - (0x15 to 0x16)
e) Uninitialized Variables - RAM - (ox17 to 0x1A)
f) Stack - RAM - (0x1E to 0x1B)

so, just after compilation

compiler assigns 'x' to 0x17
compiler assigns 'y' to 0x15
&
reserves a space in Initialized data section (0x13) and stores '10'
compiler assigns 'z' to 0x11 & stores a value of '20' in that location.
(Note: Actual storing is done after flashing the code, compiler only creates the object file)

now, the code (contents of the function) is also replaced with real addresses

say
x = y + z

x is replaced with 0x17
y is replaced with 0x15 (but this address is not yet initialized, so before this some one has to move data from location 0x13 to 0x15 - explained below)
& z is replaced with 0x11

So a assembly will instruct the processor to first fetch data from location 'z' 0x11, which is 20
then fetch data from location 'y' 0x15, which is 10
then add 10 + 20
then move that to location 'x' 0x17


It has to be noted that ROM is read only memory & cannot be changed dynamically during the execution of the program(though there are was to do it - for simplicity sake it is not considered)

RAM values can be modified (written) during program execution.

Also, once the power is removed the values in RAM are lost. Values in ROM are retained.
Hence, the question comes how can we have initialized variables!
That is program should start with a predefined value & should also allow the variable to be modified during execution.
So, solution is to allocate memory in both RAM & ROM. So, before the start of actual program, the value is copied into the RAM location from ROM location.

> If there is any confusion of require more clarity or explanation please comment.



1 comment:

one of u said...

thanks man this is so great
give me u r email @ arpitbhatnagarmnit@gmail.com we can share a lot byway i m pursuing computer eng....