Followers 0

# Question about Data segment/Code segment

## 5 posts in this topic

Consider the following piece of code running on a 16-bit microcontroller (16 bit address bus width). My questions all concern what happens before main() is called.

unsigned short foo = 156;
const unsigned short bar = 12;

int main()
{
return 0;
}

Is my understanding correct that:

1. The address locations in the heap for foo and bar are known at compile time and are stored in the data segment of the binary file
2. The sizes (memory consumption) of foo and bar are known at compile time and are stored in the data segment of the binary file
3. The values of foo and bar are stored in the data segment of the binary file, separate from the size declaration of foo and bar
4. Before main() is called, the memory for foo and bar is allocated and filled with their respective values on the heap, always at the same offsets
5. In the case of an embedded system (microcontroller), memory space for "bar" is not allocated in RAM, but is directly read from ROM when required, since it was declared const and cannot change its value.
6. In the case of an embedded system (microcontroller), memory space for "foo" is allocated in RAM and its value is copied from ROM into RAM before main() is called, from which the value can be read and written to when required later on.

My two main questions are:

1. Without starting this program, how much "disk space" do "foo" and "bar" actually consume? There obviously has to be information on what they are, what value they have, and where they will be stored in memory.
2. When hard-coding values (such as "foo=2"), how is that number "2" stored?

Thanks

1

##### Share on other sites

If you never take its address, `bar' could end up not occupying any memory at all.

1

##### Share on other sites

Thanks for all the feedback! I see it's highly hardware and compiler dependent, but I'm satisfied with the answers.

Is there a reason you are asking this question?

General curiosity. Programming micro controllers makes you realise how sparse you suddenly have to be in comparison to programming for PCs, given the limited hardware, and I simply wondered how the binary file was structured.

The particular device I'm working with is the dsPIC33FJ06GS001, in case anyone was wondering. It's one of Microchip's newer line of controllers for digital signal processing.

0

## Create an account

Register a new account