Thursday, July 19, 2007

Process Address Space




This post is not great stuff or a treasure trove of hidden secrets but the very basic things which can help you write a better User mode Application on Windows with fewer access violations.There is a lot of difference between being able to write the code that works and the code that works without throwing the disdainful access violations.Writing bug free code on windows is an art which requires the knowledge of the memory in which your application resides.


Porting your user mode code on Windows is like sending your child to a boarding school in a distant place, you better enquire about the place and send your child equipped with all it takes to survive in a foreign land.Just like the inmates of a day boarding are expected to take care of themselves Windows expects your brain child, your code to take care of itself failing which it faces the wrath of the warden, the Memory Manager.

So let us start by knowing the place, the memory allotted to the application also called the Process Address Space and how it is organised.


Each user mode process in Windows gets a Virtual Address Space of 2GB for its private use. The tiny picture you see on the right side shows how that 2GB of space is organised into segments and what does each segment contain.

Fixed Size Segments: The Text and Data segments are fixed in size and their size is decided by the size of the program to be run. The Text Segment contains the code or instructions for the CPU to execute. The fixed size data segment contains the global and Static Local Variables used in the program. These regions are generally marked read only and can not be modified by other segments.


Point to ponder: What should happen when you try to write into one of the memory locations of Code or Data segment?
Well, Windows (Operating System) being a good master and savior of these guarded (marked as Read only) territories should throw a memory access violation and stops you from going any further by terminating the offending process.
So now you know where those vicious Access Violation messages come from?


Dynamic Size Segments: Stack and heap segment both are dynamic in size. Heap grows upwards in memory (from low addresses to high addresses) and Stack grown downward (From High Addresses to Low Addresses).

2 comments:

Unknown said...

That was a good tech byte and now I know from where the fammous 'Access Violation' messages emanate from..it is interesting to see too many of these messages from the windows OS though??!! I get them on my laptop everytime I do a shutdown..Maybe the OS is being tooo much protective of the code or data segments??!

Deeps said...

gud post.. and it will be nice if u be specific to the platform being used..
it can b a very gud resource for the programmers..
all d best..