Wednesday, November 10, 2010

C Program to reverse a sentence in wordwise

Few months back, i have attended the one Product Based Company interview, 2 times within 2 months of time. First time, they have done my interview for firmware development requirement which needs in depth knowledge of memory related issues and C language knowledge related to the same. That is, xpectation was high and hence my profile didnt match. Even though they have done their duty...! With lot of good questions, i was able to get benefited by that interviews.

After 1 month of time, i got once again call for Noida requirement. When i sat infront of the interviewer, he asked me to write one C program to reverse a sentence word wise. That is, if the input is 'I am Pramod', the output should be 'Pramod am I'. When he saw my happy face, he told to write using only one loop and in optimized manner.....!!!!!

I have written as follows.

/****************************************
* 1st Version of the program
*
******************************************/
void main()
{
char str[] = "I am Pramod";
char *temp; int i;
char *ptr[10];
temp = strtok(str, ", \n");
i=0;
while(temp != NULL)
{
ptr[i] = (char*)malloc(20);
strcpy(ptr[i], temp);
temp = strtok(NULL,", \n");
i++;
}
for(i=i;i>=0;i--)
if(ptr[i]!=NULL)
printf("%s\n",ptr[i]);
}

After this, he came to know that i am working in Application layer and hence he told me that am not suitable for the required position. They wanted the people who worked on hard core OS development or Device driver/firmware developers. Also he asked me that i know JAVA. I told, i have not worked on JAVA but i have studied in academic. After he told "there is no meaning in continuing this interview process. Even though i passed this round, other people will ask hard core JAVA questions. You are good as a application programmer but we require efficient C programmers and JAVA programmers. Efficiency in Application domain is not enough for OS and below layers. I am sorry to say, u can go now...."

I was so sad and scolded the person who scheduled my interview, came back.
After some days, i was trying to write the same program in one shot. But recently, with one loop i have done....!!!

/****************************************
* 2nd Version of the program
*
******************************************/
void main()
{
char str[]="I am Pramod";
int i=strlen(str);
while(i!=0)
{
if(str[i]!=' ')
{
i--;
continue;
}
else
{
printf("%s\n",str+i);
str[i] = '\0';
i--;
}
}
printf("%s\n",str+i);
}

After this i have started to collect my friend's, colleague's ideas on this questions. After getting some ideas following program got its birth...!

/****************************************
* 3rd Version of the program
*
******************************************/
#define SWAP(T, a, b) { T t = (a); (a) = (b); (b) = t; }

char *strrev(char *s)
{
int len = strlen(s);
if (len > 1)
{
char *a = s;
char *b = s + len - 1;
for (; a < b; ++a, --b)
SWAP(char, *a, *b);
}
return s;
}

void main()
{
char *ptr;
char str[]="I Am Pramod";
ptr = strtok(strrev(str), ", \n");
while(ptr!=NULL)
{
printf("%s\n",strrev(ptr));
ptr = strtok(NULL,", \n");
}
}

Every tough questions will improve our thorughtprocess about the problem or programming languages. Our approach skills will be improved. Hence it is always recommended to attend interviews NOT ONLY to change the job . At least mock interviews with domain experts/architects will help us a lot.

If anyone of you find different logic, please drop a mail onto pramoda.ma@gmail.com

Good luck...

Thursday, October 21, 2010

Few tricky code snaps on Linked List....


Few months back, when i was started for attending interviews to get into so called software industry, my thoughtprocess was not in line. Also because of language and other non-technical issues, every question was new and challenging to answer...!


At that point of time, i have decided to get benefited from all the interviews i attend. Thats how my notes called 'Notes from Interviews, Notes for Interviews' got its birth. At that point of time, i didn't have my technical blog.

So, now i am putting some of those into my blog to get remembered and to make you all remembered...!

Data structures(stack, queues ans Linked Lists) was one of my interesting subjects. Also because of this subject only i learned something about C language. Before that, i didn't know about what printf will do, what is getch() etc. One day before of my lab exam in 1st sem, i had written each lab program 150 times to get passed in exam.....!!!!!

Other interesting thing is, to understand DS
better, i have taken DS exam twise....!!!(?) (understood)

Here, i am sharing some tricky questions on Singly linked list.


Deletion of a node whose address only known in a singly linked list.


Node_Deletion(NODE ptr)
{
NODE next;
ptr->data = ptr->link->data;
next = ptr->link;
ptr->link = ptr->link->link;
free(next);
}


Reversing a singly linked list:

void Revrse_SSL(NODE first)
{
NODE ptr, pre=0, next;
ptr = first;
next = ptr->link;

while(ptr->link)
{
ptr->link = pre;
pre = ptr;
ptr = next;
next=next->link;
}
ptr->link = pre;
}


Finding out a middle node of a singly linked list;

FindMiddleNode(NODE first)
{
NODE current, mid;
int check = 0;
current=mid=first;

while(current)
{
current = current->link;
check = (check+1)%2;
if(check==0)
mid = mid->link;
}
return mid->info;
}

There could be some other ways to do same as above. If you would like to share, drop me a mail the same.

Always welcome to comments and suggestions...

Have a great career...

------

Wednesday, October 20, 2010

Remember about memcpy/memmove, strcpy/strncpy and malloc/calloc ....!


memcpy and memmove


These memory handling functions make us to confuse when anybody asks about the same. Better to keep in my blog for me and you...!

Among these, memmove handles memory overlapping but memcpy does not.

int main()
{
char str1[]="Mera Bharat Mahan";
char str2[40];
char str3[40];
memcpy (str2,str1,strlen(str1)+1);
memcpy (str3,"copy successful",16);
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
return 0;
}

Output is:
Mera Bharat Mahan
Mera Bharat Mahan
copy successful


Look at the following code snap.

int main ()
{
char str[] = "memmove can be very useful......";
memmove(str+20,str+15,11);
puts (str);
return 0;
}

Output is: memmove can be very very useful

If we change the above code to memcpy(), then ,

int main ()
{
char str[] = "memmove can be very useful";
memcpy(str+20,str+15,5);
puts (str);
return 0;
}

output: memmove can be very very l

In case of memcpy, when address gets overlapped, then the data copy process starts from the
eginning of src string (2nd parameter). Hence memcpy is not a better function to use when
here is a possibility of address overlaps.



strcpy() and strncpy()

strncpy(str1, str2, 10);

The major drawback of strncpy() is, when u r copying data from str2 to str1, if the number of characters if less
han or equal to string length of str2, then the NULL character of str2 will not be appended and hence the values
fter strlen(str2) will remains same as it is.


void main ()
{
char ptr[] = "Raghu";
char str[] = "Pramod Mathur";
printf("%s\n", strncpy(str,ptr,5));
}

Output will be ---- Raghud Mathur

void main ()
{
char ptr[] = "Raghu";
char str[] = "Pramod Mathur";
printf("%s\n", strncpy(str,ptr,6));
}

output will be ---- Raghu


malloc() and calloc()

The difference between malloc and calloc also could be one of the interview question. Even though if we have worked 4+ years in C programming itself, it doesnt mean that we definitely used calloc and many other functions. Also, it is in out hand itself about how we utilise the library functions. Better always to use most of the functionalities of C to becaome familiar.

When you allocate a memory to a pointer using calloc, be default, the content in the memory location, will be NULL. But whereas in the case of malloc, it is not. Thats the difference between malloc and calloc.

-------------------

Please let me know if any of u found mistakes : drop a mail to pramoda.ma@gmail.com...

Gud luckckckckck......

----

Tuesday, October 12, 2010

C Program where, registers playing a role, unknowingly....!


Few days back, when I was assisting one of my colleagues in learning C language, one C program didn’t work as I expected. The program was to explain the stack concept in storing local variables.


main()
{
int a=10;
int b=20;
int *ptr;
ptr = &a;
ptr--;
printf("%d %d\n",*ptr);
}

Conceptually, a, b and ptr will be stored in stack because of its local scope. Hence address will decrement from a to b. As a result, *ptr should give the value of b. But at that point of time, it was not like that...! I was surprised...! I have tested in my machine as follows.

main()
{
int a=10;
int b=20;
int *ptr;
ptr = &a;
ptr--;
printf("%u %u %u\n", &a, &b, ptr);
printf("%d %d\n",*ptr);
}

When I tested this program, the output was as I expected. Say, 1000, 996, 996 and 20. Once again I surprised...! In my machine, the output is different and in my colleague's system, the output if different for the same program and same GCC compiler....!!!!!! Once again looked into both programs, there was no difference except address printing line. Thought that address printing line won’t affect the output.

But after some days, I have discussed this thing and I came to know that, if registers are available and if there is no explicit reference to the variables, then compiler could use CPU registers to store the local variables. Because of that only, stack operation result was reflecting in the output. When I try to print the address explicitly, then compiler should use the memory location to store the local variables. Hence stack operation was successful.

It doesn’t mean that, every compiler behaves like this. I found this behavior in GCC. There could be some other compilers which can use stack memory for storing local variables even though we don’t try to fetch the address of the variables. All depends on Compilers....

Gud luk...

Monday, September 27, 2010

About CSCOPE utility under Linux....



Few days back, i came across an utility called CSCOPE which is mainy used for code browsing, sorry, effective code browsing. Useful for debugging and maitainance type of work. Before that, i never heard about CSCOPE...!

When i was working on Maintainance project under linux environment, we were using QTCreatoir IDE which was very slow for more than 10,000 source files. It was taking too much time to search for anything. Threre is no 'Go to Definition', 'Go to declaration' type of functionalities like Visual Studio IDE. Hence struggling a lot to work with QTCreator.

At the same time, one of my colleagues, was using different utility CSCOPE, using which he was finding patterns, functions etc easility with less time. I was watching the same for some days and finally asked about the same to learn CSCOPE. Within next 5 mins, i became a user of CSCOPE....!

It is a good tool to work with more number of source files ( .C and .H files) which uses c-tags for C files.

"cscope -R"

command will create some required files and symbol tables to make searching efficient. Here 'R' means recursive.

Go to root directory of your Source Tree and give this command. After some point of time, you will get a different user input screen to enter what you want. (as in the screenshot)

When you type any pattern of function call or simple string or whatever, you will get listed of source files with lot more information. Use up and down functions to select the files and Enter. Source file will be opened in vi editor. If you exit, once you will be in the same panel.

Good tool to work with....

Enjoy...

--

Monday, July 26, 2010

About 'Const Volatile' variables in C


Since last few days, i was collecting some information about 'const volatile' variables. Because not every C programmer use this. Only few of low level Embedded Software Developers use these 'const volatile' veriables in their proffession.

Even though am a Embedded Software developer, still i didnt get chance to use 'volatile', 'const volatile' type of variables. Because, normally people who write low level programs like device drivers, firmwares, use these variables. If our programs are going to communicate directly with the hardware then we use these type of variables.

In our Embedded domain, people work in application level, middleware layer and lower layers like Firmware/Driver. But only few of us will get opportunity to use unique features of C language. When we have have constraints like memory, CPU cycles, code size, then efficiency and optimization come into picture and we will get chance to learn more in depth (not breadth). Thats what my blog's title says.

Regarding 'const volatile' variable:

This is possible and mostly used in embedded system.The example is Interrupt Status Register. As it is a status register, in the program we should not modify this variable. So it should be a constant. But this variable can be changed by the processor or hardware based on the interrupt condition. So when in the program, we want to read the value of this variable, it should read the actual value with out any optimisation. For this reason ,the variable can be declared as volatile too.

volatile int * const port_add = 0x400;

Yes we can have constant volatile variable in cases where you are using a variable value of which wont changed by your program but may change asynchronously because of some external event.

Const volatile variable shall be used in addressing the fixed memory where the address is constant and the value changes due to external events. For ex: when you want to read the data of any hardware port the address is constant and the value keeps on changing based on the external events on the port. In case of reading a hardware status register, const prevents the value from being stomped on, while volatile tells the compiler that this value can be changed at any time external to the program.

I have already given some information about the volatile variable in one of mu previous post. Please refer the same for volatile variables. I always pray to god as please give me chance to work on projects where i can learn many features of C and also, with people who worked more than 5 years in C language itself. Then only i can learn more and more.

Till now, i have worked with people who were masters in assembly language and less experience in C language. Hence when working my decisions were the final decisions. When we work with people who technically strong than us, then we can learn more. Our technical competency increases.

Dont forget to drop a mail regarding my mistakes and your suggestions...

Gud luck...


Thursday, June 17, 2010

Extra-ordinary Debugging Provisions from GCC Compiler

In Linux, one of the best and efficient debugging tools is printf statement.I think many of us know this. But i learnt the best usage of this printf statement recently. I am sharing the same with you.

When i was reading some Linux device driver code, written by one of my colleagues, i saw some different printf statements which i never seen before.

Those were like

    printf(">> %s %s %d\n", __FILE__, __FUNCTION__, __LINE__);

When i saw this code, i was trying to find out where these were declared and some information on these inside the code. After some time, discussion with my lead made me to know about this.

These are very good 'tools' provided in GCC compiler. In many cases, when we are working in Linuc/Unix environment, printf is a simple and efficient debugging tool.

Normally we use like, at the beginning of each function,

    printf(">> %s %s %d\n", __FILE__, __FUNCTION__, __LINE__);

and the at the end of each function as,

    printf("<< %s %s %d\n", __FILE__, __FUNCTION__, __LINE__);

Please look into the first characters of these printf statemtnes carefully. These statements are started with '>>' and '<<' symbols which designates the entering to the functions and leaving from the functions. These informations clearly says that, while debugging, which functions called when and when the control has come out. This information will be very very useful to find out the cause or reason for the error. At the first run itself, by looking into the output, we can suspect where the 'nonsense' is happening.

Here __FILE__ gives the filename. __LINE__ gives the line number and __FUNCTION__ gives the name of the function. These are all macros defined by default and no need to do any manual stuffs.


At the beginning of my job, i was using the printf statements only for debgging in linux. But i was not using these macros, even i didnt know about these at all....! I was using like, one printf for one run! Say, i have one main.c and other 3 C files in my project. Each 3 files having one function defined in that. If any error is coming in 3rd C file, i should go from main.c to 3rd C file to confirm that in 3rd C fille only error is occuring. To achive this, 3 printf statements and 3 runs are required. Simply waste of time. If i use above methodology, i can come to know at the first RUN itself.

I was really felt well when i came to know about these thing. Now am not writing any function without these 'mechanisms'.....

I am sure you all will definitely feel the same...

Gud LucK....

(Please drop a mail to pramoda.ma@gmail.com if u find any mistakes here)

Sunday, March 28, 2010

What is Virtual Memory?


Initially, when i heard aboout Virtual Memory, i knew that 'all current running data will in RAM. From RAM only, processor get the data. Hence addresses for those data will be different in Secondary memory (Hard Disk) and RAM. Virtual Memory hides these information ie., it converts the actual address to RAM address and vice versa.

But when, fortunately(?), I saw one document about Virtual Memory some days back, i came to know that i was wrong about Virtual Memory. Immediately i took a small note on Virtual Memroy and decided to put on my blog.


Virtual Memory:

Most computers today have 2 to 4GB of RAM available. Often, that amount of RAM is not enough to run all of the programs. For example, if you load the Windows operating system, an e-mail program, a Web browser and word processor into RAM simultaneously, RAM would not be able to hold it all.

With virtual memory, the computer can look for areas of RAM that have NOT been used recently and copy them onto the hard disk. This frees up space in RAM to load the new application. Because it does this automatically, you don't even know it is happening, and it makes your computer feel like is has unlimited RAM space.

The area of the hard disk that stores the RAM image is called a page file. It holds pages of RAM on the hard disk, and the operating system moves data back and forth between the page file and RAM. (files have a .SWP extension.)

Of course, the read/write speed of a hard drive is much slower than RAM, and the technology of a hard drive is not geared toward accessing small pieces of data at a time. If your system has to rely too heavily on virtual memory, you will notice a significant performance drop. The key is to have enough RAM to handle everything you tend to work on simultaneously. Then, the only time you "feel" the slowness of virtual memory is in the slight pause that occurs when you change tasks. When you have enough RAM for your needs, virtual memory works beautifully. When you don't, the operating system has to constantly swap information back and forth between RAM and the hard disk. This is called thrashing, and it can make your computer feel incredibly slow.

----- * -----

I had some questions on this Virtual Memory when i attended interviews. Swapping functions (call by value/call by reference) will be useful in this context. That day only, made me to know about Virtual Memory.

Interviews are not only for changing the company. They also help us a lot to improve our thought process and make us realize about how much we know about the things.

Have a great life...


Friday, February 12, 2010

Introduction to ' volatile ' keyword of C

Many people doesn't know much about volatile keyword of ANSI C. All C programmers wont use this keyword. Low level Embedded software developers, firmware developers use this keyword to play with hardware.

I got some important points on volatile keyword and i am sharing the same information with you. This will make me to get familiarized with volatile keyword.

Volatile keyword:

volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any fraction of time.

To declare a variable volatile, include the keyword volatile before or after the data type in the variable definition.

    volatile int foo;
    int volatile foo;


Now, it turns out that pointers to volatile variables are very common. Both of these declarations declare foo to be a pointer to a volatile integer:

    volatile int * foo;
    int volatile * foo;


Volatile pointers to non-volatile variables are very rare.

     int * volatile foo;

And just for completeness, if you really must have a volatile pointer to a volatile variable, then:

     int volatile * volatile foo;

Use of Volatile Keyword

A variable should be declared volatile whenever its value could change unexpectedly. In practice, only three types of variables could change:

• Memory-mapped peripheral registers
• Global variables modified by an interrupt service routine
• Global variables within a multi-threaded application

As a middleware developer or embedded software developer, i have used volatile keyword for a global variable which was shared between multiple threads (WinCE threads). Without volatile also, it was working. But for better practice, i have used once.

I think some Real-time operating systems make all variables volatile by default except constants.

I think this much is enough to know about Volatile keyword.

Good luccccccccccccck.........

Saturday, January 9, 2010

Some Simple C Programs To Play With Bits

I like programming ie., development. Since my proffessional career started, i am working on C programming only. Thats why always i will be working on C programming. I like to work on Programming.

While working on bit related programming like setting a bit, resetting a bit in an integer, i was getting confusions. Concept and theory will be present in my mind but i will take too much time to produce on paper. Programming on the IDE or any programming tool will be easy. But to write on a paper, me like people feel little difficulty.

Hence i have written some programs and the same i am giving here. This could be helpful to many to understand bits.

1. Program to make a bit 0 if it was 1 and to make 1 if it was 0

void BitToggle()
{
    int Data, Bit;
    int t1,t2;

    printf("Enter the data \n");
    scanf("%d",&Data);

    printf("Enter the bit number to be toggled\n");
    scanf("%d",&Bit);

    if((Data >> Bit) & 0x01) //if bit is set
    {
    Data &= (~(1 << Bit));
    }
    else //if bit is not set
    {
    Data |= (1 << Bit);
    }
}

This logic is very simple and you would get a better logic than this. But this is a good program to start work wround bits. I think no explaination is required for this.


2. Program to reverse the bit order of an integer

void ReverseBitOrder()
{
    for(i=0;i<32;i++)
    {
        p = data >> i; //'data' is the value to be reversed
        t = p & 1; // 'p' and 't' are temporary variables
        result = result | (t & 1);
        result <<=1;
    }
}

This is a good program to play with bits. Also, at firt time, it has taken some more time to do this. First i have tried on a paper. But after doing program only i could able to do because of debugging.

I think these are good programs to start work around bits in C.

Goooooooooood luccccccccccccck

----

Friday, January 1, 2010

Static functions in C

While discussing with my friends, I came to know that I have not understood properly about static functions in C language. I felt uncomfortable about static functions and decided to go through once again and make it perfect.

static void function() //Hidden from other files if not included
{
}

I knew about static functions that the static functions cannot be called from other files of the same workspace. But I tried the same but it didn’t work. That means I was able to call static functions from other files. But after reading one article on static functions, I felt that I was doing some mistakes.

Hence immediately sat with Visual C++ IDE and started to work on that. Created a project and added 2 source files, written main() function and added functions and also a static function.

I came to know the best example for the static functions which is DLL files in Windows. As already I have shared some information about the DLLs and their creation in my previous posts. In DLLs, we will export the functions in definitions (.def) files. We can call those functions only dynamically. Using definition files, we are making some functions public that means allowing to call them from outside the module. If we have some functions in our DLLs which are used by our DLLs only and they are not supposed to call from other than DLLs, those will not come into definition file.

In the same way the static functions are. If we make some functions ‘static’ in one file, those cannot be called from other than this file. In this way we are hiding some functions by from other files my making these as ‘static’.

The mistake what I was doing at first time that I was including the source file (.c file) which was having static functions in other file from where I was calling static functions. Without including the source files, static functions cannot be called.

But all files should be in the same workspace.

What could be the main use of static functions? This was my next question. One of the forums discussion article helped me in this regard.

Say we are writing one module which will have 100 functions required by other modules. But the same module will have other 15 functions which are internal functions called or used by the module itself. Then they will be ‘static’ functions. When we compile the all this file with out own source file in our workspace, whether it may be Linux or Windows IDE software, we are able to call only 100 function which are non static. I think, API functions of Operating systems are like this only. APIs should be non static. All APIs could be using their internal functions which will be static ie., hidden from outside world.

After all these, I felt OK on static functions.

Please drop a mail to Pramoda.ma@gmail.com for any mistakes, suggestions, clarifications or anything.

Good luck.