Thursday, October 29, 2009

How does a C Program Work/Execute


How does a C program works :

Note : Following article is based on my understanding of the chapter "Basic Memory Management" , from book Operating Systems , Third Edition by Gary Nutt .

This article describes the various Stages your C code or Program goes through before producing the desired output .

Stage 1 :
Writing of code or program and saving it with “.c” extension .

Stage 2 :
Compile Time : Now you need to compile your program .
In simple terms its job is to check whether your code follows all the rule of the C language (any language for that matter) i.e errors like , related to syntax and declariations etc are not present and convert the code into a language which is understood by your computer .

Let us now explore the compilation process in a bit more detail :

Aim of compile time is to produce a Relocatable Object Module , commonly known as an object file, with extension “.o” .
For a C program relocatable object module has has three logical blocks of addresses :



  1. A Text Segement (also known a Code Segment) , which contains a block of machine instructions .


  2. Data Segment , which is a block of Static Variables .


  3. Stack Segment , which represents the stack which is used while program is in execution .

Now the relocatable object module contains the relative addresses of the various code segments .
For example if you have used a user defined function “foo()” , which is also present in the same file , then it will contain its relative entry address.

However , for funtions like “printf()” or any other function, whose definition is not present in the in the code that you have written , compilier is not able to get their relative addrsses at the Compile time, so what is does it annotate each such reference to an external address , so that linkeditor can place correct addesse at the link time.

Stage 3 :
Link time : Now at link time code and data segments of each relocatable object module are combined to form the absolute module or the load module .
Link editor combines all the datasegment into single data segment and all code segment into a single code segment.
When datasegments are combined the relative addresses of individual static variables are changed. The linkage editor then relocates the addresses in the instructions so that they reference the uptodate addresses in the aggregated data segment .All the undefined addresses references are found by linkage editor as it combines the relocatable module: the resulting composition includes all the program text and data, so that every reference to the data or program entry point is resolved .

The absolute program is stored in a file(in the secondary memory) until a process is ready to use it.
image : courtesy operating system, third edition, Gary Nutt

Stage 4 :
Load time : Now when a process is allocated to use the absolute module , memory manager allocates a block of primary memory to the process. Then the loader copies the absolute program and data into the newly allocated memory.

Now the interseting part is , till now all the adderesses in the absolute program file were relative , starting from 0 , but now program is at some particular Physical address in the primary memory , so Loader Translates all internal logical primary memory addresse , with zero being replaced by the Physical memory address , and othe addresses changed according to it .

At this stage the program is called Executable program , the one expected by the hardware control unit , just before it is added to the primary memory at the proper location. The PC (program counter) is set to the primary memory address of the first ececutable insrtuction i.e. Main enry point for the program .

Now the program is ready to Run , the Static and Dynamic binding concepts which also play an important role , but beyond the scope of this article . May be in some other article :)

References : Operating Systems ,Third Edition by Gary Nutt.





Sunday, October 18, 2009

Thoughts Of MY OWN ... !

its important to learn from your mistakes ...... but its more important to remember what you have learned.

- Samarth Gupta


overcome your fears ... they are not that dangerous as they seem to be ... !

- Samarth Gupta

Three people can never be Best Friends to each other ...

- Samath Gupta

... I have Dreams ... and I am ready to fight for them ..... !

- Samath Gupta

..... In the end you have only Three true Friends .... your Mother .... Father ... and MONEY ... !

- Samath Gupta

Every one wants to hear the TRUTH .... only condition is it should not be about Himself ... !

- Samarth Gupta

Never answer a Question .... which is not addressed to you .... !

- Samarth Gupta

Got Bored of EARTH .... planning to go back Home .... !

- Samarth Gupta

If humans, the most intelligent of all beings can't understand each other then wats the point

- Sandeep Bhaskar

my opinion about above thought :

humans understand each other very well ... the point is they dont like what they have understood .... !

- Samarth Gupta

Wednesday, September 23, 2009

Enjoy Your Coffee....

A group of alumni, highly established in their careers got together to visit old university professor. Conversation soon turned into complaints about stress in work and life.

Offering his guest coffee, professor went to the kitchen and brought a large pot of coffee and assortment of cups- porcelain, plastic, glass, crystal. Some plain looking, some expensive and some exquisite, telling them to help themselves to hot coffee.

When all the student had a cup of coffee in hand professor said-
If you noticed, all the nice looking expensive cups were taken up leaving behind the plain and cheap ones. It is normal for you to want only the best for yourself But that is the source of your problem and stress.

What all of you wanted was coffee, not the cup, but you consciously want for the best cup and were eyeing each other’s cup.

Now if life is coffee, than jobs, money and position in society are the cups. They are just tools to hold Life, but the quality of Life doesn’t change. Sometimes by concentrating only on the cup we fail to enjoy the coffee in it.

So don’t let the cups drive you….

Enjoy the coffee instead.

Tuesday, September 22, 2009

printf() interview question ....

Look at the code below.


void main()
{
if(X)
{
printf("Hello");
}
else
{
printf(" World");
}
}



What should X be replaced with inorder to get the output as "Hello World"?



Friday, August 21, 2009

Using pointers for double dimension memory allocation OR Dynamic Memory allocation for Multidimension Array

Many times you need to allocate dynamic memory for a multidimensional array in C language. This article deals with using pointers for dynamic memory allocation for two dimensional array , which can further be extended for higher dimensions.

Example of situation when u require 2-D dynamic allocation :

1. Take the input dimension of an matrix form the user and then get input values and print them.

2. Print a magic square after taking dimensions form user.

3. Implementing Hash Table after taking hash value form user.

I will try to explain the concept by solving the first problem (simply coz its the easy to solve :) and also for others to understand )

Problem Statement : Take the input dimension of an matrix form the user and then get input values and print them.

Solution :

first i will paste a working solution and the explain it :

i tried to copy paste the code but it gave some html error ... so im pasting the image ..... will soon find some way to post the code :)

please right click and open the image in a tab to see the code


Explanation :

Problem is we need to take input from the user at run time , so we cannot declare a 2-D array of fixed dimensions before hand , we need to do it at runtime , using dynamic memory allocation.

For this we use the concept of pointer to a pointer or Double pointer.

Now to revise the basics we can use a normal pointer to allocate memory for an array , i.e. a single dimension array. It can be done in following manner.

int *array;
int arraysize;
printf("enter the size of array");
scanf("%d ",&arraysize);

array=(int *)(malloc(sizeof(int)*arraysize));

what happened above is when i said int *array a pointer named array was assigned to point to a location where some int is supposed to reside. But by writing

array=(int *)(malloc(sizeof(int)*arraysize)) i have allocated memory dynamically equal to the arraysize given by the user, where each element is integer type.

if we analyze the right hand side of the statement:

array=(int *)(malloc(sizeof(int)*arraysize));

(int*)
typecast the memory allocated to be a pointer to a integer, since array is of that type .

malloc(sizeof(int)*arraysize)
dynamically allocates a memory of elements equal to arraysize and each element of size int , since sizeof(int) is used.

so in the end what we have is a single dimension array, whose base address is pointed by pointer array.

Now coming to the code that i have posted above for 2-D array :

the part of the code that deals with the 2-D dynamic allocation is :



these three lines are the only lines which u need to understand to get the concept :

Line 1: matrix=(int**)(malloc(sizeof(int*)*no_of_rows));

The variable matrix which is a integer pointer to a pointer is allocated memory allocated equal to no_of_rows and each of type pointer to an integer. So what we have now is an Array of integer Pointers of size equal to no_of_rows .

since matrix is a double pointer so we need to typecast the memory allocated to its type by (int**) and since we are allocating memory for array of pointers so we use sizeof(int*)
.

Line 2 :


this is a simple for loop which is responsible to run the line below it no_of_rows time, so that each integer pointer from Array of Pointer can point to integer array itself .

Line 3 : *(matrix+i)=(int*)(malloc(sizeof(int)*no_of_column));

By *(matrix+i) we go to each integer pointer in the array of pointers for which we allocated memory in the Line: 1.

By (int*)(malloc(sizeof(int)*no_of_column)) we first typecast the allocated memory since *(matrix+i) is of type integer pointer we use (int*)
and now we want to store integers in the allocated space to we use sizeof(int) .

That all the memory is allocated, rest of program is simple input and display.

For any more clarification feel free to comment.










Thursday, August 20, 2009

Format USB drive / Pen Drive on LINUX - Ubuntu

Step 1:
insert the pendrive in the USB port and wait for it to be detected (or mounted according to Linux)

once it is mounted (ie it opens in a window) , go to the terminal and type the following command :

$ df -h

it will display the list of all mounted drives on your system. It will look something like image shown below :


now very carefully note the path for your pendrive , it would be written in front of the name of your pendrive. Like in above example the data to be noted is /dev/sdb

it might be in your case something else like /dev/sd1
Note: be very sure that you get the correct name otherwise you will end up formatting some other drive

Step 2:

Unmount the USB or Pendrive.
It can be done in two ways :

1. simply right click on pendrive icon on desktop and unmount.
or by
2.form terminal run following command :

$ sudo umount /dev/sdb

i prefer the second method since if pendrive is unmounted after command you can be sure you got the correct drive name in step 1.

Remember : you r only supposed to unmount the pendrive not to remove form the usb port.

Step 3 :

run the following command from the terminal :

$ sudo mkfs.vfat -I /dev/sdb

which will format the pendrive. If you want to provide and label or name to ur pendrive use following :

$ sudo mkfs.vfat -n "name/label" -I /dev/sdb

replace
"name/label" with the name u want to give to usb drive
Now ur pendrive is formatted.

Note: u can format in any file system u wish to by replacing vfat by that name example ext3 .

Wednesday, August 19, 2009

Difference between NULL and NUL

Difference Between NUL and NULL in C Language :

Hi Everyone.....

i seems no matter how much C language you learn it seems it will never end....
i found a very interesting difference between NUL and NULL in C language while going through a book which i would like to share:

NULL is an pointer with value zero (0) , that is you can say it does not correspond to a real memory location in your program. For linux operating system it is defined as ((void *)(0)) .

Whereas NUL is an character with integer value 0 (zero) . It is this NUL character you keep hearing about which comes at the end of every string as "\0" or "(char)(0)" and takes a memory space equal to that of a character .

so to remember NULL is a pointer and NUL is a character :)

About Me

My photo
Hi Friends, I am Samarth currently pursuing my Masters degree in Information Technology from International Institute of Information Technology ,Bangalore .