Thursday, October 22, 2009

Good skills for people

All of us want good communication skills, interpersonal skills, social skills, leadership skills and soft skills. Success in any business, occupation or profession depends on 85% of people skills. Lot of people fail in life because they haven't mastered the skills with people. All your personality depends on relation with other people. To be more happy we should not be more intelligent.

Following are important points in dealing with people.

1) Understanding the human ego.

In the heart of everyone there is some thing which demands respect. We are more interested in ourselves. Every person wants to feel important. If you like yourself then you will like others. We should fulfill others ego by giving respect and approval. To get good from people, their basic needs should be fulfilled. For e.g. if a person is hungry, we should give him food first because they cannot give attention to other things. when the ego-hunger is satisfied and when they are in high self esteem they are cheerful, generous, tolerant and willing to listen to others. when self esteem is low they think negative, they talk a lot, they show-off ( deliberately behave to attract attention) and they become aggressive. With genuine compliments and real praise you can feed the ego of low esteem people. create the habit of giving five sincere compliments each day. Every person help or may not help depends on own ego. Help others like themselves better. Satisfy their hunger for self-esteem.

2) The importance of making others feel important.

It is within your power to make them like themselves better. It is within your power to make them feel appreciated and accepted. Always give respect and nice with people makes them feel important. You must recognize the other person. Give credit for suggestions. Encourage others. Don't criticize employees in front of others. Ask employees for their opinions. Inform employees for their progress. Think other people are important. when you are trying to deal with a group try to acknowledge everyone in group. Notice people when you get time. Don't try to compete with any one. If you want to impress any one let them know that you are impressed by them. when some body insults you, ask yourself does it make any real difference. Don't try to win battles if it is related to ego.

3) Controlling the Actions and Attitudes of others:

You have to adopt the attitude you want others to express. When you want to get out of an explosive situation keep your voice as soft as possible don't wait until other person gets angry. Always act confidently. To get confidence you have to believe in yourself and act confidently to get others belief in you. Moderate your tone of voice. smile from within.

4) Creating a good impression:

When you are dealing with others set the stage depends on situation. Before going to any kind of discussion ask yourself what do i really want from this. what mood i should have. create the tone according to that. Don't worry what others think because the world forms its opinion of us largely from the opinion we have of ourselves. If some body asks you in which company you are working, if u can't say the name of company say the quality of the company which you like. For e.g: I work in one of top five IT companies. Never go for competition with any one. If you want to make a good impression boost your own product. If you want others should yes to you, Good rule is ask some preliminary questions for which they must say yes. Then ask big question for which they say yes.

5) Acceptance, Approval and Appreciation:

Attracting people with Acceptance, Approval and Appreciation.
Acceptance: Accept others as they are,
Approval: See the things which are good in others.
Appreciation: show their good values in them. some ways of appreciation are

  • Don't keep them waiting.
  • If there is someone you cannot see immediately, acknowledge their presence.
  • Thank people.
  • Treat them as special.
6) Communicate Effectively:

Get people talking about themselves.
  • Ask questions like Where are you from? what do you think of our weather? What business are you in? If any body says I work in a software company near to majestic. Don't ask directly about software company, ask first where is majestic. then ask which software company. Always show you are interested in themselves. If some body tells lets talk about yourself. what do u think about my working domain. topic is related to you but he is talking.
  • Talk about yourself when you are invited and asked. Talk little bit about yourself but don't overdo it. use me too technique. If someone says I was raised on a farm and you say "I was too". Any thing about you or your past that is similar to others will help them to like you. Always use happy talk. If any thought disturbs you write it in a paper burn it, repeat it three times.
7) Listening:

when you are listening what they are saying, then they think that you are smart. Listening makes you clever. People will tell you what they want if you will listen. Listening helps overcome self-consciousness. You should know what people want, what they need and who they are in order to deal them effectively. Practice the art of listening:

  • look at the person who is talking.
  • Nod your head
  • Lean forward
  • Ask questions.
  • Don't interrupt.
  • Stick to the speakers subject.
8) Getting people to Agree:

  • Listen to them completely, pause before answering, Don't try to win 100%, State your idea moderately and accurately, Speak through third parties like Statistics, records, history and quotes. To say others are wrong say like this " I felt the same way about it at first, After getting more information it changed my complete picture.
  • Giving Praise: Thank people with their names by looking at them. If you want to be happy look good things in people. praise must be sincere, praise the act or attribute rather than the person.
9) Criticizing others without offending them:

Criticism must be made in absolute privacy. Preface criticism with kind word or compliment, criticize the act, not the person. If you do any mistake say, I don't know what is expected of me. Ask for cooperation, don't demand it for e.g. Will you make these corrections?. One criticism to an offense ( don't criticize again and again) , Finish in a friendly fashion ( I know i can count on you).

Wednesday, September 23, 2009

Networking Interview Questions and Answers

what is Socket? how it is created?

A socket is one end of a two-way communications link between two programs running on the network.

Creation of sockets is done using the socket() system call.

int socket(int address_family, int socket_type, int proto_family);


address_family defines the type of addresses we want this socket to use.

socket_type could be the type of interaction (and type or protocol) we want to use.

proto_family selects which protocol we want to socket to use. We will usually leave this value as 0 (or the constant PF_UNSPEC on some systems), and let the system choose the most suitable protocol for us. As for the protocol itself, In the Internet address family, a socket type of SOCK_STREAM will cause the protocol type to be set to TCP. A socket type of SOCK_DGRAM (Datagram socket) will cause the protocol type to be set to UDP.

The socket system call returns a file descriptor which will be used to reference the socket in later requests by the application program. If the call fails, however (due to lack of resources) the value returned will be negative (note that file descriptors have to be non-negative integers).

As an example, suppose that we want to write a TCP application. This application needs at least one socket in order to communicate across the Internet, so it will contain a call such as this:


int s; /* descriptor of socket */
s = socket(AF_INET, SOCK_STREAM, 0);


How to Associate a connection with Socket?

After a socket is created, it still needs to be told between which two end points it will communicate. It needs to be bound to a connection. There are two steps to this binding. The first is binding the socket to a local address. The second is binding it to a remote (foreign) address.

Binding to a local address could be done either explicitly, using the bind() system call, or implicitly, when a connecting is established. Binding to the remote address is done only when a connection is established. To bind a socket to a local address, we use the bind() system call, which is defined as follows:


int bind(int socket, struct sockaddr *address, int addrlen);

There are 4 possible variations of address binding that might be used when binding a socket in the Internet address family.

The first is binding the socket to a specific address, i.e. a specific IP number and a specific port. This is done when we know exactly where we want to receive messages. Actually this form is not used in simple servers, since usually these servers wish to accept connections to the machine, no matter which IP interface it came from.

The second form is binding the socket to a specific IP number, but letting the system choose an unused port number. This could be done when we don't need to use a well-known port.

The third form is binding the socket to a wild-card address called INADDR_ANY (by assigning it to the sockaddr_in variable), and to a specific port number. This is used in servers that are supposed to accept packets sent to this port on the local host, regardless of through which physical network interface the packet has arrived (remember that a host might have more than one IP address).

The last form is letting the system bind the socket to any local IP address and to pick a port number by itself. This is done by not using the bind() system call on the socket. The system will make the local bind when a connection through the socket is established, i.e. along with the remote address binding. This form of binding is usually used by clients, which care only about the remote address (where they connect to) and don't need any specific local port or local IP address. However, there are exceptions here too.

How to send and receive data from sockets?

int read(int socket, char *buffer, int buflen);
int write(int socket, char *buffer, int buflen);


The return value may be:

0 - The connection was closed by the remote host.
-1 - The read system call was interrupted, or failed for some reason.
n - The read system call put 'n' bytes into the buffer we supplied it with.

what are different types of Socket?
Stream Sockets, Datagram Sockets, Raw Sockets, Packet Socket.

what is ICMP?
Internet control message protocol is used by hosts and gateway to send notifications of datagram problems to sender. It uses echo test to check whether it is responding or not.

what is Router? How to Design a router?
Router is used to route packets from one network to other.

what is Gateway? How to Design a gateway?
Conversion from one protocol to another.

what is network protocol time?

The Network Time Protocol (NTP) is a protocol for synchronising the clocks of computer systems over packet-switched, variable-latency data networks. NTP uses UDP as its transport layer. It is designed particularly to resist the effects of variable latency.

what situation packet goes into infinite loop?
If ttl value in IP header is not properly decremented at every router.

what protocol is used to retrieve mails?
POP3 and IMAP4 are used to retrieve mails.
IMAP4 stores a copy of message on the server whereas POP3 does not.

what is IP tunneling? how it works?
IP tunneling (IP encapsulation) is a technique to encapsulate IP datagram within IP datagrams, which allows datagrams destined for one IP address to be wrapped and redirected to another IP address. IP encapsulation is now commonly used in Extranet, Mobile-IP, IP-Multicast, tunneled host or network.

what is tcp 3 way handshaking?
Client starts active open after passive open in server side in TCP. The client sends SYNC, then the server send SYNC+ACK, last client send ACK.

What are the different type of networking working devices?

Repeater:
Also called a regenerator, it is an electronic device that operates only at physical layer. It receives the signal in the network before it becomes weak, regenerates the original bit pattern and puts the refreshed copy back in to the link.

Bridges:
These operate both in the physical and data link layers of LANs of same type. They divide a larger network in to smaller segments. They contain logic that allow them to keep the traffic for each segment separate and thus are repeaters that relay a frame only the side of the segment containing the intended recipent and control congestion.

Routers:
They relay packets among multiple interconnected networks (i.e. LANs of different type). They operate in the physical, data link and network layers. They contain software that enable them to determine which of the several possible paths is the best for a particular transmission.

Gateways:
They relay packets among networks that have different protocols (e.g. between a LAN and a WAN). They accept a packet formatted for one protocol and convert it to a packet formatted for another protocol before forwarding it. They operate in all seven layers of the OSI model.

what is frame relay? which layer it comes?
Frame relay is a packet switching technology, it comes in data link layer.

what are the names of PDU in higher layers?

Transport layer: segment.
Network Layer: packet.
Data link layer: frames.
Physical layer: bits/ bytes.

Thursday, September 10, 2009

How to Debug Using gdb

Debugger:

After executing the binary executable we some times get unexpected results. The errors may be of dangling pointers, Stack over flow, Divide by zero etc, Which are very difficult to debug by looking at the Source code. GDB is a tool to debug the program it supports various languages like c,c++ etc.

gdb can take core dump file or executable file. Here executable is executed in the context of gdb. To debug using gdb at compilation time we have to give -g option.

gcc -g source.c -o source

Note: Electrical fence is used to check boundary errors. like size of array is 30 and we are storing value at 40 th location.
gcc source.c -lefence

After allocating memory using malloc, Always allign the memory using memalign. To avoid type casting.

Running a executable in gdb: gdb a.out
The you will get a gdb prompt.
The following commands has to be typed at gdb prompt.

run or r is used to run the program.
step is used to step by step execution, it also oes inside the function.
next is used to avoid function debug.


passing parameters: set args fastrevision blogspot
showing the arguments: show args
debug a already running program: attach process-id.
To get information about threads: info threads

Checkpoint: Setting a book mark to return that place easily.
checkpoint [lineno][function name]
during creation of checkpoint it saves all register, Stack values , Variables etc.

After executing some code.

To return back to check point: restart checkpoint-ID.
To know information about checkpoints: info checkpoints.
To delete checkpoint: delete checkpoint checkpoint-ID.

Listing of Program

To know your program where it is currently Running.
gdb> list

Note: To know the return value of previously executed program.
echo $?
Successful execution returns 0. Abnormal termination of program returns more than 0.

Breakpoint

To break the progrm after executing for some time. break command is used. For eg:
break lineno, function Name, Address.
while giving line numbers it always takes the first default file. To specify the file.
break file.c:

To add some condition: break 14 if ptr==0
To break the program only once: tbreak lineno
To get information about breakpoints: info breakpoints.
To ignore break point for some time: ignore breakpoint_no count.
To clear the breakpoint: clear [location][function name].
To disable break points: disable [breakpoints] [1..10]
To enable break points: enaable [breakpoints] [1..10]
We can execute some commands when it reaches a break point. By giving commands and end.
Commands is used to give commands which are in between commands and end to shell prompt.

Watch Points

To know what are the values. expression may be location,variable etc.
watch expression
rwatch expression
awatch expression
info watchpoints

To get information

ptype a: display what is the type of a.
info main
info source.

Saturday, September 5, 2009

Internet Protocol of TCP/IP

Internet Protocol:

IP packets are send by the help of TCP, UDP, ICMP etc. The IP packets are connection less and unreliable. if any problem occurs in network( like router is not responding ) it simply sends ICMP packet to the source. The reliability is provided by upper layers i.e TCP.

The IP header:


The most significant is at 0 and least significant bit at 31. Hence it is called big-endian byte order.
Data is transmitted from left to right i.e from 0 to 31.

Vers: It tells what version of IP packet it may be 4 or 6 according to the requirement.
IHL: The no of 32 bit words used in the header including any options. Normal value for this field is 5.
TOS: This tells the type of service of the packet. It tells minimum delay, maximum throughput, maximum reliability, minimize monetary cost. XXXUUUU0.

Total Length: This is the total length of IP Datagram in bytes. It is possible to send 65535 size packets, but the link layer divides in into small packets using fragmentation.

Indentification: This value is increased while sending packets continuously. This is mainly used in fragmentation. Reassembly program at the other end is used to combine the fragmented packets.

Time to live:A no which tells the no of routers through which this IP datagram is passed. When ii reaches to zero. The send is informed with an ICMP message indicating destination is not reachable.

Protocol: Which protocol gave the data to IP to send.

Option Field: This field is defined for
Security and handling restrictions.
Record route: Each router record its IP Address.
Time stamp: ( how long the router will keep the recorded IP Address).
loose Source routing : Specifies list of IP Address that must be traversed by datagram.
strict source routing : Specifies the list of fixed ip Address to be traversed. ( It is rarely used, All router may or may not use this feature).

Subnetting: The process of dividing hostid into small subnets is called subnetting.

eg:
IP Address: 192.168.40.33, subnet Mask: 255.255.255.224 this means each subnet network is in the gap of 32 Addresses.
therefore subnet ID is : 192.168.40.32 and host ID is: 1

How to Achieve Success in Life

Success can be many things, Success means better life, Success means finding real happiness, Remember one thing size of success is limited to size of thinking. If you think small your success is also small or if you think big and believe in yourself your success will be big.

  • Belief : Always think positive, Person belief is known by the way he talks,walks and acts. you grows small in the group of people if you don't have belief what you do. Always generate positive thoughts from your mind. you can't sell a product if you can't believe in yourself. All discoveries are made because they have self belief in themselves. Successful people are ordinary people they believe in themselves what they do.
  • This is some thing which takes time, No body going to help you, you have to work hard and achieve it.
  • Three components are important in life. What you are going to do. How you accomplish your goal and the results will be greater respects from your friends and family, greater status, Increase in income and standard of living is higher.
  • The place you work is a laboratory, It includes the people you work, you talk and yourself. This place is for you to work to achieve your goal. See the difference in successful and unsuccessful persons.
  • The more successful the person is, The more less excuses he makes. Every unsuccessful person says I don't have time I am fully busy. Every body has got 24 hours it mainly depends how they utilize it effectively. In a year you have got 8760 hours.Total hours sleeping in a year= 2738.Total hours eating in a year= 730. Total hours in phone and chatting = 900. Total hours in traveling = 730. If a person is spending this much of time in all these activities, why they are saying I don't have time. Successful people don't say i don't have time. Successful people always like to face challenges. A successful person knows success is a extra effort and hard work.
  • Successful people never tell any health excuses. No body is interested to know about your health. If you say i feel great you get more confidence in yourself.
  • Always be happy with what you have. For example if you are getting less pay, you can say at least i have job for living.
  • Never give age excuses like i am too old to do this or I am too young to do this. There are lot of people who got success after lot of age. Age is not a barrier it is an excuse. Believe that you can handle any kind of responsibility.The productive age is from 20 to 70. Invest your future time in really what you want to do.
  • The only thing you should have interest and enthusiasm. Its not important how much intelligence you have.It is most important how you use your intelligence. Attitude is more important than intelligence. Always think the better ways of doing things. Always use your mind to get solution.
  • People are measured not by their money, family support, friends or job he is doing. People are measured the way they think. Clearing all obstacles which stop you to think big. Think what are your major attributes that helps you in getting success. For example if anybody else is getting promotion compare with him what are the qualities you are lacking. Try to improve those qualities for e.g. if your colleague has good communication skills and try to improve that one to add in yours assets for getting success. you create a kind of your image in others with the words you speak. So always use positive words.
  • Practicing give value to things around you. If you give value to these things then you can also give value to peoples. Small things matters for a Successful person.
  • Also think creative. new, better and improved ways of doing things. Success at home, work and society are important.They are many creative ways of doing things.
  • Before you begin your work think how can i do better work today. Improve quality and quantity of your work.
  • Eliminate the word impossible from your thinking and speaking vocabulary. Take a task which is difficult and write down the reasons you can't do it. Try to work out on the reasons. Man goes where he wants to go. Take risk in doing the things. There is no one best way to do things. Always welcome new ideas. Expose yourself to new restaurants, New books, new friends. Do some thing different in weekends. Be progressive. Get up a hour earlier for planning the daily activities.
  • Achieving high level of success requires support of others. To achieve support of others: See things from their eyes, think as if your in the other side. Always handle the things as a human way.
  • Being a good listener is very important in life. Listening gives us more information to make important decisions. To practice listening encourage others to talk in personal or group meetings. Ask about tell me about your experiences, what you think to done about this and what you think the key point here. Do information research. Concentrate in others what they said. Always ask yourself how you can I do this better, how can i do more.
  • Fear is biggest enemy. It decreases our mental ability. It makes people sick. It closes your mouth when you want to speak in public. No one is born with confidence. Action cures fear. Before taking action think that is it correct and human way of doing things. When ever you feel fear think that what kind of action I should take to avoid fear. There are some fears which can't be avoidable in such time play with small kids, go for a movie, Put some extra work in some special project. Biggest fear is that what other people say and think about you.
  • Give value to your ideas by acting in it. Action improves your confidence. Before thinking of task. Go and do that task. for e.g. Going for a Movie. Doing exercise etc. Be active not passive. Be a doer. Don't wait until the conditions are perfect to act. Get more ideas but these ideas are valid when you act on it.
  • Successful people meets the problems and work out on difficulties when they do arise. Cross bridge when you come on it.
  • Always store positive thoughts in mind. Always think about positive things that happened with you through out the day before you go to bed. Always think positive if you get negative thoughts try to divert you mind from that.
  • Fear on other people is a big fear. To overcome that fear you have to keep the people in proper prospective. Other people are basically like you so there is no reason to fear. Other person is important as much as you are. Every person as his own problems, desires etc. Understanding attitude is very important in life if some body insults you and scolds you simply think that this person is having a bad day. Control your fire. We can change our attitude by changing our physical attitude.
  • Always sit in front seat. Always maintain eye contact. walk 25% faster. practicing speaking up. Speak up at every opportunity. Every open meeting you attend speak up. Every family gathering speak up. Make a contribution. Make a suggestion. Ask a question. Speak slowly and clearly. Smile big to improve your confidence.

Thursday, August 27, 2009

Static and Dynamic Linker

Linker: A program that links one or more object or relocatable files and results in binary executable. Linking done in two forms.

Static linking:
Executable built with libraries at build time. Every time we create a new executable depending on platform.

Dynamic linking:
Linking with libraries at run time. Easy designing, change of code, update etc. These files are first loaded in memory and then linked. Dynamic code is shared between multiple applications.

Important library for C programming is libc.

The library file created with extension .a or .so .
In UNIX environment file name having .a extension called as static library and for .so as dynamic library.

In windows environment dynamic library as .dll extension and static as .libs extension.

Creating a Static and dynamic library in LINUX:
Tool for creating library is ar (library compressed tool).

create source files like first.c and second.c
create relocatable executable files like
gcc -c first.c -o first.o
gcc -c second.c -o second.o
ar rcs lmine.a first.o second.o

Note: rcs stands replace create symbol(variable,function name etc).

Relocatable binary is created in two forms.
position dependent.
position independent.

Above created static library is position dependent.
Position independent code can be created using
gcc -c -fpic first.c -o first.o
gcc -c -fpic second.c -o second.o

gcc -shared -o libmine.so first.o second.o

files which showed in green color required permision for load.

/usr/lib is a default libary repository.
/usr/include is a default header repository.

while using the static or dynamic library we have to create a header file which contains the function prototype.

gcc -I./ app.c -o app

search for include files in current directory.
for using library
gcc app.o -o app -lmine.a
it search in default directory /usr/lib
for searching in current directory.
gcc -c app.o -o app ./mine.a

here we can see, it is having static library but it is also linking some dynamic library called libc etc.

for linking statically give -static option during creation of binary executable.
when we find the object dump we get more information how it linked.

objdump -D app | more

linker creates procedure address table, It contains dynamically linked function and address of it.

Dynamic or Shared libraries can be used by an application as a load time library or run time library. Load time library mainly loaded during init.

load time libraries are those which are loaded during process initialization and remains resident through out the process execution time.

libraries are called as run time when they are loaded by functionality.
it mainly avoid direct reference to library.

for example the source is in mandl.c

void (*ptr) ( void);

void *libptr=dlopen("./mylib.so",RTLD_NOW);
ptr=dlsym(libptr,"func");
ptr(void);
dlclose(libptr);
gcc mandl.c -o mandl -ldl

RTLD_LAZY is used when it takes much time in execution.

Binary Image:
Binary image are of 3 types.

1) Linkable( relocatable).
2) Loadable( shared library with position independent).
3) Executable( functionality + runtime ).

functionality further divided into instruction and data.
each part of binary image is loaded into each block of memory(stack, BSS, Code and data).
To read the header information of binary file objdump or readelf is used.

.text contains all instructions.
.data contains only initialized global variable, static variables etc.
.bss uninitialized global data.
.rodata contains read only data. No write operation performed in this.
other sections are linker specific.
each .o file has section header table.
linker combines all section header table into single program header table with matching the same flags.

The header table in executable binary is called program header table.
loader mainly use this header table to load into process address space.

Various flags in sections.

PROGBITS: code,data,debug information.
SYMTAB and DYNSYM: Symbol table.
STRTAB: String table.
etc.

How a binary executable loaded into memory.
  • Think that we want to execute program1.For execution we have to write ./program1
  • The shell receives this request to run a program, Checks for the existence of file.
  • It verifies the Application Binary Interface(ABI). To know ABI type readelf -a
  • It every thing is fine it call loader to load the program.
  • Loader checks the program header table part of elf header.
  • Using the kernel memory allocator it allocates memory block in user space and maps the segments in executable image.
  • Calls the kernel process manager to carry process registration.
  • It allocates structures to keep track of information i.e TCB ( task control block) named as task_struct.
  • A valid process id is given.
  • The process control block is en queued to run queue. ( depends on different queue different run queues are used).
  • Depending on the scheduler it selects PCB from run queue.
  • During runtime it adds a section named as stack.
Application Booting up Procedure:
  • Booting of application starts with an init routine. Initializer is responsible for intilising of stack segment and loading of shared objects or libraries. Link loader is resposible for loading all shared libraries.
  • Before loading it resolves all symbols of program header table. During loading of shared libraries symbol entries in PL table are updated with absolute address.
  • after initialization it calls main program.
  • Process detach is responsible for detaching shared libraries from process. It also releases the stack segment assigned to it.

Wednesday, August 26, 2009

Stages of Compilation in Linux

A Source file is compiled and linked to form a executable binary file for execution in a architecture.Understanding the various stages of compilation helps in cross compilation of code.
for e.g. below steps shows compilation process using GCC compiler.

Source file:
It contains the Source program in text format. it can be of any langaue c,c++ etc.
for e.g. first.c is a C Source code.

Preprocessing:
it helps in creating fast and efficient code.
It reads from header files for creating a preprocessed source file.
All macros and constant symbols are replaced.
All conditional preprocessor directives are processed by preprocessor.
It provides conditional compilation.

gcc -E first.c -o first.i

The know the steps of preprocessing in console. compile using
gcc -v -E first.c -o first.i
v stands for verbose.

Assembler
: Takes preprocessed file and creates .s file called as assembly file.
it is mainly required for optimization(speed and space) of code.
for e.g. gcc -v -S first.i -o first.s

Relocatable Binary
:

gcc -c first.s -o first.o
Contains offset address of the assembly code, it is assigned at compile time.
object dump of first.o shows offset address.
for eg: A relocatable code contains call 19 <> .Its position depends on main position.
This file contains source in assembly and library routines.


Executable Binary:
gcc first.o by default it creates a.out else we can give as gcc first.o -o first

This loadable file contains loadable address in the form of segment and offset called as absolute address.Function calls entries present in PLT called as procedure linkage table.
executable file contains some run time library. This file is mainly created by linker which is OS dependent.

From executable binary to loadable binary code is created by
objdump -D first
for seeing in page wise- objdump -D first | more

File Format: To know the format of file, file command is used.

for e.g.
file first.c
it shows as text file.

file first.i
it shows as text file.

file first.s
it shows as Assembly file.

file first.o
it shows as binary file.

These set of tools are called tool chain. Cross compilers mainly required for executing the code in different architectures. The object dump of binary executable contains the loadable address.

The creation of files from .c to .o is can be used in any architecture.
.exe or binary executable is platform and architecture specific.

The executable has three flags:
suid: process keeps information about uid. if this flag is set.
sgid: process keeps information about gid. if this flag is set.
sticky: if this flag is set means requesting kernel to keep in memory after execution.

during execution of executable binary it is stored in process address space.
process address space contains different segments of memory like data,code,stack etc.

During runtime three key functions are performed.
--init
Resource allocation is done here.it calls different resource allocation routines.it calls specific kernel system calls.

--start
make a call to main and handover the control to functionality.

--fini
release of all resources allocated by init.

if system is crashed due to some bug in the kernel modules. The --fini routine is not called and resources are not deallocated. The parent will become a zombie process and performs all cleanup.

relocatable code is executed in various platform by a interface called as Runtime.
(Relocatable code .o file) functionality->unix runtime->binary(elf format with no extension)-> unix OS.
(Relocatable code .obj file) functionality->windows runtime->binary(coff format with .exe extension)->Windows OS.

Runtime layer also called as Application Binary Interface.

Tuesday, July 7, 2009

Linux Device Drivers Introduction

Linux started as the hobby of a Finnish college student named as Linus Torvalds in 1991. Early it supported 386 processor later it is metamorphed to support multiple architectures some of the major supported architecture are X86, IA64, ARM, PowerPC, Alpha, SPARC etc.

Linux Kernel:

Linux is an open source kernel maintained by a set of software volunteers called kernel hackers.
It is developed by different open source developers across the world.
www.kernel.org is a official website for kernel source code under a license called GPL(general public license).

Advantages of Linux

Free of cost, Fully customizable in all its components, Linux is powerful, It has low failure rate, We can reduce kernel image to a small size, highly compatible to many operating systems, well supported.
The linux source code has one folder named as arch. Which contains names of all platforms. for e.g. alpha, arm, cris, i386 etc.

e.g. of linux source having version 2.6.10.1 means,
first number 2 rarely change.
second number 6 shows stable.
third no shows added new code.
fourth no shows solution to bugs by putting patches.

Types of Kernel:

Kernels can be classified into four broad categories: monolithic kernels, microkernels, hybrid kernels and exokernels.

Monolithic kernels: Which have traditionally been used by Unix-like operating systems, contain all the operating system core functions and the device drivers. Modern monolithic kernels, such as those of Linux and FreeBSD, both of which fall into the category of Unix-like operating systems, feature the ability to load modules at runtime, thereby allowing easy extension of the kernel's capabilities as required, while helping to minimize the amount of code running in kernel space.

A microkernel usually provides only minimal services, such as defining memory address spaces, interprocess communication (IPC) and process management. All other functions, such as hardware management, are implemented as processes running independently of the kernel. Examples of microkernel operating systems are AIX, BeOS, Hurd, Mach, Mac OS X and MINIX. Applications cannot access other memory address space without API's. Accessing a device require many context switches.

Hybrid kernels include additional code in kernel space to share common data in single address space. It mainly avoid context swithes. Most modern operating systems use hybrid kernels, including Microsoft Windows NT, 2000 and XP.

Exokernels are a still experimental approach to operating system design. They provide no hardware abstractions on top of which applications can be constructed. This separation of hardware protection from hardware management enables application developers to determine how to make the most efficient use of the available hardware for each specific program. Exokernels in themselves they are extremely small. However, they are accompanied by library operating systems, which provide application developers with the conventional functionalities of a complete operating system. A major advantage of exokernel-based systems is that they can incorporate multiple library operating systems, each exporting a different API (application programming interface), such as one for Linux and one for Microsoft Windows, thus making it possible to simultaneously run both Linux and Windows applications.

Platform virtualization :

It hides the physical characteristics of operating system from the users,it shows aother platform for running other platforms.

types :

Full virtualization: without modifying of OS.

Hardware Assisted virtualization: separate Hardware support is needed.

Partial virtualization: Address space virtualization.

Para virtualization : API's are provided between virtual machine and hardware.

Operating system level virtualization: OS is modified to run various paltforms.

Linux Vendors(Distributors):

kernel source is modified to create different operating systems.

1) Server OS: RHEL(Red Hat Enterprise Linux).

2) Desktop Distribution: Fedora, General Ubuntu, Suse linux, Centos.

3) Multimedia OS: Debian linux, Qlinux.

4) Embedded Distribution: monto Vista, Bluecat linux.

5) Real time linux: timesys,linco,Vxworks,uClinux,Windriver.

6) Mobilisation : Android OS.

Evaluation Assurance Level:

At what level the system was testing to meet the goal. It has EAL1 to EAL7 levels.

EAL1: Functionally Tested.
EAL2: Structurally Tested.
EAL3: Methodically Tested and Checked.
EAL4: Methodically Designed, Tested, and Reviewed.
EAL5: Semiformally Designed and Tested.
EAL6: Semiformally Verified Design and Tested.
EAL7: Formally Verified Design and Tested.



Glossary

Absolute Path: Path from root or drive is called Absolute path or Complete path. In Linux it started as / .
Device Driver: Small programs that allow the operating system to interact with hardware devices, such as disk drives, video cards and printers.
PCMCIA: Personal Computer Memory Card International Association is a small card attached with PC for wireless connectivity and other features.
Relative Path: A path from current directory. for e.g. in linux it is showed as ./ .
Router: A device which connects two networks.IP packets are sent to one network, if the destination not present in that network than it is passed to other network.
IETF: Internet Engineering task force tells about the requirements in protocol.
TIMERS: Timers are mainly required to invoke specific periodic functions called restransmissions, Delayed acknowledgement or round trip time.
Round Trip Time: After sending packet the sender times how much time it take to get acked.if failed to get ack. Stack increses RTO( Retransmission time out).further after increasing RTO if we won't get any ack,RTO is increased again this process of increasing RTO for retransmission is called back-off.
VSSC: Vikram Sarabhai Space Center at Tiruvanthapuram is responsible for the launch vehicles.

Sunday, July 5, 2009

Common English Sentences for Speaking

I sleep late.
Early evening i like to have snacks.
while working i took siesta some times.
Sometimes people scoff at me when i talk.
Maximum all americans are blondes.
all our friends are in congregation in lunch time.
I was a copycat in the age of 17.
A mental person was taken to asylum.
I beg your pardon.
Excuse me for disturbing you at home.
I'm sorry to disturb you again,but I need some details.
Sorry to interrupt.
I'm Sorry, if I have distressed you by asking all this questions.
Sorry,I'm late.
Don't talk rubbish.
Don't talk nonsense.
that's ridiculous.
you must be joking.
Don't talk ambiguous.
Life is not money making.

Word Meaning

pier: A platform built by vertical pillars near sea shore for docking of ships and boats.
siesta: A nap in the early afternoon.(while working i took siesta).
scoff: laugh with disregard.
cannery: A place where food is canned(packed).
preacher: A person who is preaching to gospel(unquestionable truth).
congregation: A group of people.
jigsaw puzzle (puzzle in box to get some figure).
copycat: person who copies habit and behavior of others.
blonde: a person with fair skin and hair.
ramson: money demanded for a return of a captured person.
asylum: A hospital for unbalanced person.

Sunday, April 5, 2009

Link Layer of TCP/IP Protocol

  • Link Layer
Link layer mainly concerned with the sending and receiving the IP packets of IP module,ARP request an reply for ARP module,RARP request and reply for RARP module.Link layer varies depends on the type of network we are using for eg: Ethernet,TokenRing,FDDI,Serial etc.

Ethernet Frame
Description :
It is an encapsulation of Ethernet header to various packets such as IP packet,ARP,RARP,DATA etc.
Destination Address : 6 bytes MAC Address.
Source Address : 6 bytes Source MAC Address.
Length field follows address if it is 802 packet else it contains type follows data.
for Ethernet 802 packet minimum data size is 38 and for 803 it is 46.




SLIP (Serial Line Internet Protocol)

It is a Encapsulation of IP packet,data etc. SLIP is mainly used to connect with internet through RS232 serial port cable almost present in all types of PCS.
SLIP is terminated with special SLIP_END character that is 0xC0. If 0xC0 character is present in actual data it is replaced with 0xdb, 0xdc. If db is present in actual data it is replaced with 0xdb, 0xdd.

Deficiencies of SLIP
-> Each end must know others IP Address.
->SLIP packet can be transmitted in any protocol because we are not using any type field.
->There is no Checksum.

PPP (Point to Point Protocol)

The format of PPP looks like

The frame begins and end with a flag whose value is 0x7e, address whose value is always 0xFF and a control byte with a value of 0x03. protocol field tells the type of data it can store.

if protocol equals to 0x0021 means information field of an IP datagram.
if protocol equals to 0xc021 than it is link control data.
if protocol equals to 0x8021 than it is Network control data.

Maximum Transfer Unit:

There is a limit on the size of frame for both Ethernet encapsulation(1500) and 802.3 (1492) encapsulation.

FDDI- 4352.
Ethernet- 1500 .
IEEE 802.3/802.2 - 1492.

path MTU : It is the maximum transfer unit between two hosts at short interval. It always change depends on the different network.
if one is Ethernet and other is 802.3.

Thursday, April 2, 2009

TCP/IP Tutorial and Technical Overview

  • Introduction
This tutorial is helpful for understanding TCP/IP stack,Writing Network programs,Network System administration, Writing TCP/IP applications. TCP/IP is a collection of layers.Each layer contains some list of protocols which perform specific function. Generally TCP/IP contains 4 layers.

  1. Application Layer : mail,telnet
  2. Transport Layer : UDP,TCP
  3. Network Layer : IP,ICMP,IGMP
  4. Link Layer : Drivers
Link layer sometimes called as data link layer or network interface layer.They handles all types of hardware details.

Network layer(internet layer) is used for routing of packets between various networks.

Transport layer provides data transmission between hosts.In transport layer two protocols are used
transmission control protocol and User Datagram protocol.

  1. TCP : Reliable transmission of data between two hosts,Exchange of acknowledge takes place for reliable transmission. We can easily set the timeout for the transmission.Application should not have to put any effort to check data reliability.
  2. UDP : Unreliable flow of data.Some mechanism in application layer has to be implemented to check reliability.
Application layer is mainly at user level and other three layers are at kernel layer.


when one or more computers connected together it forms LAN. When two or more networks are connected together it is called as Inter Network or Internet. The hardware which is used to connect two networks is called as Router. Example of network are Ethernet, Token ring, FDDI ( Fiber distributed data Interface). Router connects Network at Network layer but Bridge connect different networks at datalink layer.Bridges makes appearance of multiple network to upper layer as same Network.
  • Internet Address
Internet address contains 4 bytes. Internet address is divided into 5 classes.
Easy way to remember is shift one bit from the left to right by adding 1's.














Class A : Range : 0.0.0.0 to 127.255.255.255

Class B: Range :128.0.0.0 to 191.255.255.255

Class C: Range : 192.0.0.0 to 223.255.255.255

Class D: Range : 224.0.0.0 to 239.255.255.255
(Multicast Group Id)

Class E:Range : 240.0.0.0 to 247.255.255.255 ( Reserved for future use)

The Internet Network interface Center is responsible for assigning the IP Address to Various Networks.

IP Address is divided into three parts:
1) Unicast : Only for single host in a Network.
2) Multicast : set of hosts in a Multicast Group.
3) Broadcast: All the hosts in a given Network.

DNS: Domain Name System is a Distributed database that provides the mapping between IpAddress and hostname. For remembering of Hostname Easily.

Adding headers to the data is called Encapsulation and removing headers is c
Application to transport layer : Plain Data.
Transport to IP layer : TCP Segment.
IP layer to Network layer : IP segment
Network layer to link layer: frames.

Network always contains one Client and one Server.
Client send request and server process the request in 2 ways either iterative or concurrent way.

Iterative one request at a time.Concurrent Many request at a time.

Port Numbers are mainly used to identify the type application we are working. The well known port numbers are from 0 to 1023. for eg : ftp on port 21, telnet 23,tftp on 69 etc.The well known port numbers of TCP/IP are managed by Internet Assigned numbers Authority.

Epemeral ports: These are port numbers which can be used by Applications in their hosts. Every Application port must be unique.Most TCP/IP applications use epemeral ports in the range from 1024 to 5000.
Some examples of reserved ports are:
echo = 7 ( server sends whatever client sends).
discard = 9 ( Server discards whatever client sends).
daytime = 13 (server sends date and time to client in human readable form).

Internet = collection of hosts around the world that communicate using TCP/IP
internet = multiple networks connected together using common protocol suite.

Sunday, March 29, 2009

C Programs with Solution Logic

  • Transpose of a Matrix
Interchanging the Rows with Columns or Vice-Verse
for(i=0;i&k;i++)
for(j=i+1;j&l;j++)
{
temp=mat[i][j];
mat[i][j]=mat[j][i];
mat[j][i]=temp;
}
  • Finding the Saddle point of a Matrix
A matrix a is said to have a saddle point if some entry a[I][j] is the smallest value in the ith row and the largest value in the jth column. A matrix may have more than one saddle point.

for Eg:
7 6 5
1 8 1
2 9 2

Here saddle Point value is 5.

  • How to find year is leap year.
if a year is divisible by 4 and not by 100 is called leap year.
if a year is divisible by 400 is called leap year.

  • How to swap two variables without using temporary variable?
a^=b^=a^=b

How to know system is using little Endian or Big Endain?
int i=1;
if( * (char *)&i == 1)
printf("Little Endian");
else
printf("Big Endian");

Introduction to Arrays Sorting

  • Introduction about Array
Array is a sequence collection of elements are of same type.The elements of array are accessed by index.
Array can be 1 dimensional or n dimensional.

In C Array declaration is in the form:
char name[100];

Here char is the data type and name is the base pointer of array.
The Base pointer of array cannot be changed.The Compiler treats it has constant pointer.

Array is used in application like storing list of records. etc
Arrays are used to implement various types of programs and algorithms like sorting,tress,Graphs etc.

  • Merging two sorted list
Algorithm
1) Take three Arrays A1,A2 and C1.
2)Compare each elements of A1 with A2,During comparing of elements,if 1st less than 2nd one,Then insert the 1st one C1 else 2nd one into C1. The Array from which the element is taken for insertion in third list,Increment the index of that Array.
3)Repeat step 2 for all the elements in the Array.If you get Nth index in any of the Array then go to step 4.
4) Insert the non finished Array directly in the Third array.
4) The third Array contains the list of sorted elements.
  • Bubble Sort
1) take a array and Compare first two elements,If greater swap with other element.So at last we get largest element in nth location.
So no of Comparisons required is n-1 first time.

Like that total comparisons are (n-1)+(n-2)+--------1= n(n-1)/2.
Order = O(n^2);
  • Quick Sort
1)Quick sort is the fastest sorting algorithm.
2)Take a Array of elements.Consider the first element as pivot.
3) traverse from left if the current element is greater than pivot,stop there.
4) traverse the list from right,if no is less than pivot,wait there.
4)Swap the two wait locations elements.
5) traverse the list again until their traverse won't cross with each other.
6) always traverse from left first.
7) if they cross with each other,swap the right location value with pivot.
8) two lists are formed now.
8) 0 to right and left to n-1.
9) perform quick sort again on two lists.

Average time complexity of Quick sort is O(nlogn).
worst case time complexity = O(n^2). ( always one of list is empty).
worst case space complexity =O(n). ( every time list splits into two).
  • Selection Sort
  1. Find the minimum value in the list
  2. Swap it with the value in the first position
  3. Repeat the steps above for remainder of the list.
Timing Complexity: worst=best=average=O(n^2).

Tuesday, March 24, 2009

C Aptitude Multiple Choice Questions and Answers

Q1. What will be the output of the following arithmetic expression ?

5+3*2%10-8*6

a) -37
b) -42
c) -32
d) -28

Q2. What will be the output of the following statement ?

int a=10; printf("%d &i",a,10);

a) error
b) 10
c) 10 10
d) none of these

Q3. What will be the output of the following statement ?

printf("%X%x%ci%x",11,10,'s',12);

a) error
b) basc
c) Bas94c
d) none of these

Q4. What will be the output of the following statements ?

int a = 4, b = 7,c; c = a = = b; printf("%i",c);

a) 0
b) error
c) 1
d) garbage value

Q 5. What will be the output of the following statements ?

int a = 5, b = 2, c = 10, i = a>b
void main()
{ printf("hello"); main(); }

a) 1
b) 2
c) infinite number of times
d) none of these

Q7. What will be the output of the following statements ?

int x[4] = {1,2,3}; printf("%d %d %D",x[3],x[2],x[1]);

a) 03%D
b) 000
c) 032
d) 321

Q8. What will be the output of the following statement ?

printf( 3 + "goodbye");

a) goodbye
b) odbye
c) bye
d) dbye


Q9. What will be the output of the following statements ?

long int a = scanf("%ld%ld",&a,&a); printf("%ld",a);

a) error
b) garbage value
c) 0
d) 2

Q10. What will be the output of the following program ?

#include
void main()
{ int a = 2;
switch(a)
{ case 1:
printf("goodbye"); break;
case 2:
continue;
case 3:
printf("bye");
}
}

a) error
b) goodbye
c) bye
d) byegoodbye



Q11. What will be the output of the following statements ?

int i = 1,j; j=i--- -2; printf("%d",j);

a) error
b) 2
c) 3
d) -3

Q12. What will be the output of following program ?

#include
main()
{
int x,y = 10;
x = y * NULL;
printf("%d",x);
}

a) error
b) 0
c) 10
d) garbage value

Q13. What will be the output of following statements ?

char x[ ] = "hello hi"; printf("%d%d",sizeof(*x),sizeof(x));

a) 88
b) 18
c) 29
d) 19

Q14. What will be the output of the following statements
?
int a=5,b=6,c=9,d; d=(ac?1:2):(c>b?6:8)); printf("%d",d);

a) 1
b) 2
c) 6
d) 8

Q15. What will be the output of the following statements ?

int i = 3;
printf("%d%d",i,i++);

a) 34
b) 43
c) 44
d) 33

Q16. What will be the output of the following program ?

#include
void main()
{
int a = 36, b = 9;
printf("%d",a>>a/b-2);
}

a) 9
b) 7
c) 5
d) none of these


Q17)
int testarray[3][2][2] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
What value does testarray[2][1][0] in the sample code above contain?

a) 11
b) 7
c) 5
d) 9

Q18)

void main()
{
int a=10,b=20;
char x=1,y=0;
if(a,b,x,y)
{
printf("EXAM");
}
}
What is the output?

1) XAM is printed
2) exam is printed
3) Compiler Error
4) Nothing is printed

Q19)

What is the output of the following code?
#include
void main()
{
int s=0;
while(s++<10)>
# define a 10
main()
{
printf("%d..",a);
foo();
printf("%d",a);
}
void foo()
{
#undef a
#define a 50
}

1) 10..10
2) 10..50
3) Error
4) 0

Q21)

main()
{
struct
{
int i;
}xyz;
(*xyz)->i=10;
printf("%d",xyz.i);
}
What is the output of this program?

1) program will not compile
2) 10
3) god only knows
4) address of I

Q22)
What would be the output of the following program?
#include
main()
{
char str[]="S\065AB";
printf("\n%d", sizeof(str));
}


1) 7
2) 6
3) 5
4) error

Q23)
What will be the value of `a` after the following code is executed
#define square(x) x*x
a = square(2+3)
1) 25
2) 13
3) 11
4) 10

Q24)
#include
void func()
{
int x = 0;
static int y = 0;
x++; y++;
printf( "%d -- %d\n", x, y );
}

int main()
{
func();
func();
return 0;
}

What will the code above print when it is executed?
1)
1 -- 1
1 -- 1
2)
1 -- 1
2 -- 1
3)
1 -- 1
2 -- 2
4)
1 -- 1
1 -- 2

Q25)

long factorial (long x)
{
????
return x * factorial(x - 1);
}
With what do you replace the ???? to make the function shown above return the correct answer?
1)
if (x == 0) return 0;
2)
return 1;
3)
if (x >= 2) return 2;
4)
if (x <= 1) return 1;

Q 26)

int y[4] = {6, 7, 8, 9};
int *ptr = y + 2; printf("%d\n", ptr[ 1 ] );

What is printed when the sample code above is executed?

1) 6
2) 7
3) 8
4) 9 .

Q27)

int i = 4;

switch (i)
{

default: ;
case 3:
i += 5;
if ( i == 8)
{
i++;
if (i == 9) break;
i *= 2;
}
i -= 4;
break;

case 8:
i += 5;
break;
}
printf("i = %d\n", i);

What will the output of the sample code above be?

1) i = 5
2) i = 8
3) i = 9
4) i = 10


Answers:
1.(a)-37
2.(d)none of them
3.(b)basc
4.(a)0
5.(c)infinite number of time
7.(c)032
8.(d)dbye
9.(b)garbage value
10.(a) error
11.(c) 3
12.(b)0
13.(d) 1 9
14.Error
15.(b)4 3
16.(a) 9
17.(a) 11
18.(d) nothing will be print
19.(3) Error
21.(2)10
22.(2) 6
23.(3) 11
24.(4)1..1,1..2
25.(4)if(x<=1)return 1;
26. (4) 9
27.(1) i=5

C Aptitude Questions and Answers

Predict the output or error(s) for the following:

1.
void main()
{
int const * p=5;
printf("%d",++(*p));
}
Answer:
Compiler error: Cannot modify a constant value.
Explanation:
p is a pointer to a "constant integer".

2.
main()
{
char s[ ]="man";
int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
Answer:
mmmm
aaaa
nnnn
Explanation:
s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea.

3.
main()
{
float me = 1.1;
double you = 1.1;
if(me==you)
printf("I love U");
else
printf("I hate U");
}
Answer:
I hate U
Explanation:
For floating point numbers (float, double, long double) the values cannot be predicted exactly.

4.
main()
{
static int var = 5;
printf("%d ",var--);
if(var)
main();
}
Answer:
5 4 3 2 1
Explanation:
When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively.

5.

main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
}
Answer:
SomeGarbageValue---1
Explanation:
p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array.

6.

main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}
Answer:
Compiler Error
Explanation:
You should not initialize structure variables in declaration.

7.

main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}
Answer:
Compiler Error
Explanation:
The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.

8.
main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}
Answer:
hai
Explanation:
\n - newline
\b - backspace
\r - linefeed

9.
main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
Answer:
45545
Explanation:
The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the evaluation is from right to left, hence the result.

10.
#define square(x) x*x
main()
{
int i;
i = 64/square(4);
printf("%d",i);
}
Answer:
64
Explanation:
the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64

11.
main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}
Answer:
ibj!gsjfoet
Explanation:
During the execution of printf p points to last null character and all the content also got incremented.
p1 prints the incremented content.

12.

#define a 10
main()
{
#define a 50
printf("%d",a);
}
Answer:
50
Explanation:
The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.

13.

#define clrscr() 100
main()
{
clrscr();
printf("%d\n",clrscr());
}
Answer:
100
Explanation:
Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrscr() to 100 occurs.The input program to compiler looks like this :
main()
{
100;
printf("%d\n",100);
}
Note:
100; is an executable statement but with no action. So it doesn't give any problem

14.
main()
{
printf("%p",main);
}
Answer:
Some address will be printed.
Explanation:
Function names are just addresses,main() is also a function. So the address of function main will be printed. %p in printf specifies that the argument is an address. They are printed as hexadecimal numbers.

15.

char *someFun1()
{
char temp[ ] = “string";
return temp;
}
main()
{
puts(someFun1());
}
Answer:
Garbage values.

16.

void main()
{
char far *farther,*farthest;
printf("%d..%d",sizeof(farther),sizeof(farthest));
}
Answer:
4..2
Explanation:
the second pointer is of char type and not a far pointer

17.

main()
{
int i=400,j=300;
printf("%d..%d");
}
Answer:
400..300
Explanation:
printf takes the values of the first two assignments of the program. Any number of printf's may be given. All of them take only the first two values. If more number of assignments given in the program,then printf will take garbage values.

18.

main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
}
Answer:
H

19.

main()
{
int i=1;
while (i<=5) { printf("%d",i); if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf("PP");
}
Answer:
Compiler error: Undefined label 'here' in function main
Explanation:
Labels have functions scope, in other words The scope of the labels is limited to functions. The label 'here' is available in function fun () Hence it is not visible in function main.

20.

main()
{
int i=1,j=2;
switch(i)
{
case 1: printf("GOOD");
break;
case j: printf("BAD");
break;
}
}
Answer:
Compiler Error: Constant expression required in function main.
Explanation:
The case statement can have only constant expressions .Enumerated types can be used in case statements.

21.

main()
{
int i;
printf("%d",scanf("%d",&i)); // value 10 is given as input here
}
Answer:
1
Explanation:
Scanf returns number of items successfully read and not 1/0. Here 10 is given as input which should have been scanned successfully. So number of items read is 1.

22.

#define f(g,g2) g##g2
main()
{
int var12=100;
printf("%d",f(var,12));
}
Answer:
100

23.

main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
Answer:
M
Explanation:
p is pointing to character '\n'.str1 is pointing to character 'a' ++*p meAnswer:"p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10. then it is incremented to 11. the value of ++*p is 11. ++*str1 meAnswer:"str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. both 11 and 98 is added and result is subtracted from 32.
i.e. (11+98-32)=77("M");

24.
main()
{
extern int i;
i=20;
printf("%d",sizeof(i));
}
Answer:
Linker error: undefined symbol '_i'.
Explanation:
extern declaration specifies that the variable i is defined somewhere else. The compiler passes the external variable to be resolved by the linker. So compiler doesn't find an error. During linking the linker searches for the definition of i. Since it is not found the linker shows an error.

25.

main()
{
printf("%d", out);
}
int out=100;
Answer:
Compiler error: undefined symbol out in function main.
Explanation:
The rule is that a variable is available for use from the point of declaration. Even though a is a global variable, it is not available for main. Hence an error.

26.

main()
{
extern out;
printf("%d", out);
}
int out=100;
Answer:
100
Explanation:
This is the correct way of writing the previous program.

27.

main()
{
show();
}
void show()
{
printf("I'm the greatest");
}
Answer:
Compier error: Type mismatch in redeclaration of show.
Explanation:
When the compiler sees the function show it doesn't know anything about it. So the default return type (ie, int) is assumed. But when compiler sees the actual definition of show mismatch occurs since it is declared as void. Hence the error.

28.
main()
{
int i=-1;
+i;
printf("i = %d, +i = %d \n",i,+i);
}
Answer:
i = -1, +i = -1
Explanation:
Unary + is the only dummy operator in C. Where-ever it comes you can just ignore it just because it has no effect in the expressions (hence the name dummy operator).

29.

What are the files which are automatically opened when a C file is executed?
Answer:
stdin, stdout, stderr (standard input,standard output,standard error).

30.

what will be the position of the file marker?
a: fseek(ptr,0,SEEK_SET);
b: fseek(ptr,0,SEEK_CUR);

Answer :
a: The SEEK_SET sets the file position marker to the starting of the file.
b: The SEEK_CUR sets the file position marker to the current position of the file.

31.

main()
{
char name[10],s[12];
scanf(" \"%[^\"]\"",s);
}
How scanf will execute?
Answer:
First it checks for the leading white space and discards it.Then it matches with a quotation mark and then it reads all character upto another quotation mark.

32.

What is the problem with the following code segment?
while ((fgets(receiving array,50,file_ptr)) != EOF);
Answer & Explanation:
fgets returns a pointer. So the correct end of file check is checking for != NULL.

33.
main()
{
char *cptr,c;
void *vptr,v;
c=10; v=0;
cptr=&c; vptr=&v;
printf("%c%v",c,v);
}
Answer:
Compiler error (at line number 4): size of v is Unknown.
Explanation:
You can create a variable of type void * but not of type void, since void is an empty type. In the second line you are creating variable vptr of type void * and v of type void hence an error.

34.

main()
{
char *str1="abcd";
char str2[]="abcd";
printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));
}
Answer:
2 5 5

35.

main()
{
char not;
not=!2;
printf("%d",not);
}
Answer:
0

36.

#define FALSE -1
#define TRUE 1
#define NULL 0
main() {
if(NULL)
puts("NULL");
else if(FALSE)
puts("TRUE");
else
puts("FALSE");
}
Answer:
TRUE
Explanation:
Preprocessor doesn't replace the values given inside the double quotes. The check by if condition is boolean value false so it goes to else. In second if -1 is boolean value true hence "TRUE" is printed.

37.

main()
{
int k=1;
printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");
}
Answer:
1==1 is TRUE
Explanation:
When two strings are placed together (or separated by white-space) they are concatenated (this is called as "stringization" operation). So the string is as if it is given as "%d==1 is %s". The conditional operator( ?: ) evaluates to "TRUE".

38.

main()
{
int *j;
{
int i=10;
j=&i;
}
printf("%d",*j);
}
Answer:
10
Explanation:
The variable i is a block level variable and the visibility is inside that block only. But the lifetime of i is lifetime of the function so it lives upto the exit of main function. Since the i is still allocated space, *j prints the value stored in i since j points i.

39.

main()
{
int i=-1;
-i;
printf("i = %d, -i = %d \n",i,-i);
}
Answer:
i = -1, -i = 1
Explanation:
-i is executed and this execution doesn't affect the value of i. In printf first you just print the value of i. After that the value of the expression -i = -(-1) is printed.

40.
main()
{
register i=5;
char j[]= "hello";
printf("%s %d",j,i);
}
Answer:
hello 5
Explanation:
if you declare i as register compiler will treat it as ordinary integer and it will take integer value. i value may be stored either in register or in memory.

41.

main()
{
int i=5,j=6,z;
printf("%d",i+++j);
}
Answer:
11
Explanation:
the expression i+++j is treated as (i++ + j)

42.

struct aaa{
struct aaa *prev;
int i;
struct aaa *next;
};
main()
{
struct aaa abc,def,ghi,jkl;
int x=100;
abc.i=0;abc.prev=&jkl;
abc.next=&def;
def.i=1;def.prev=&abc;def.next=&ghi;
ghi.i=2;ghi.prev=&def;
ghi.next=&jkl;
jkl.i=3;jkl.prev=&ghi;jkl.next=&abc;
x=abc.next->next->prev->next->i;
printf("%d",x);
}
Answer:
2
Explanation:
above all statements form a double circular linked list;
abc.next->next->prev->next->i
this one points to "ghi" node the value of at particular node is 2.

43.

struct point
{
int x;
int y;
};
struct point origin,*pp;
main()
{
pp=&origin;
printf("origin is(%d%d)\n",(*pp).x,(*pp).y);
printf("origin is (%d%d)\n",pp->x,pp->y);
}

Answer:
origin is(0,0)
origin is(0,0)
Explanation:
pp is a pointer to structure. we can access the elements of the structure either with arrow mark or with indirection operator.
Note:
Since structure pointer is globally declared x & y are initialized as zeroes

44.

main()
{
char *p;
int *q;
long *r;
p=q=r=0;
p++;
q++;
r++;
printf("%p...%p...%p",p,q,r);
}
Answer:
0001...0002...0004
Explanation:
++ operator when applied to pointers increments address according to their corresponding data-types.

45.

aaa()
{
printf("hi");
}
bbb(){
printf("hello");
}
ccc(){
printf("bye");
}
main()
{
int (*ptr[3])();
ptr[0]=aaa;
ptr[1]=bbb;
ptr[2]=ccc;
ptr[2]();
}
Answer:
bye
Explanation:
ptr is array of pointers to functions of return type int.ptr[0] is assigned to address of the function aaa. Similarly ptr[1] and ptr[2] for bbb and ccc respectively. ptr[2]() is in effect of writing ccc(), since ptr[2] points to ccc.

46.

main()
{
int i =0;j=0;
if(i && j++)
printf("%d..%d",i++,j);
printf("%d..%d,i,j);
}
Answer:
0..0
Explanation:
The value of i is 0. Since this information is enough to determine the truth value of the boolean expression. So the statement following the if statement is not executed. The values of i and j remain unchanged and get printed.

47.

main()
{
int i;
i = abc();
printf("%d",i);
}
abc()
{
_AX = 1000;
}
Answer:
1000
Explanation:
Normally the return value from the function is through the information from the accumulator. Here _AH is the pseudo global variable denoting the accumulator. Hence, the value of the accumulator is set 1000 so the function returns value 1000.

48.

int i;
main()
{
int t;
for ( t=4;scanf("%d",&i)-t;printf("%d\n",i))
printf("%d--",t--);
}
// If the inputs are 0,1,2,3 find the o/p
Answer:
4--0
3--1
2--2
Explanation:
Let us assume some x= scanf("%d",&i)-t the values during execution
will be,
t i x
4 0 -4
3 1 -2
2 2 0

49.

main()
{
int a= 0;int b = 20;char x =1;char y =10;
if(a,b,x,y)
printf("hello");
}
Answer:
hello
Explanation:
The comma operator has associativity from left to right. Only the rightmost value is returned and the other values are evaluated and ignored. Thus the value of last variable y is returned to check in if. Since it is a non zero value if becomes true so, "hello" will be printed.

50.

main()
{
unsigned int i;
for(i=1;i>-2;i--)
printf("c aptitude");
}
Explanation:
i is an unsigned integer. It is compared with a signed value. Since the both types doesn't match, signed is promoted to unsigned value. The unsigned equivalent of -2 is a huge value so condition becomes false and control comes out of the loop.

51.

What are the following notations of defining functions known as?
i. int abc(int a,float b)
{
/* some code */
}

ii. int abc(a,b)
int a; float b;
{
/* some code*/
}
Answer:
i. ANSI C notation
ii. Kernighan & Ritche notation

52.

main()
{
char *p;
p="%d\n";
p++;
p++;
printf(p-2,300);
}
Answer:
300
Explanation:
The pointer points to % since it is incremented twice and again decremented by 2, it points to '%d\n' and 300 is printed.

53.

void main()
{
int k=ret(sizeof(float));
printf("\n here value is %d",++k);
}
int ret(int ret)
{
ret += 2.5;
return(ret);
}
Answer:
Here value is 7

54.

void main()
{
unsigned giveit=-1;
int gotit;
printf("%u ",++giveit);
printf("%u \n",gotit=--giveit);
}
Answer:
0 65535

55.

void main()
{
int i;
char a[]="\0";
if(printf("%s\n",a))
printf("Ok here \n");
else
printf("Forget it\n");
}
Answer:
Ok here
Explanation:
Printf will return how many characters does it print. Hence printing a null character returns 1 which makes the if statement true, thus "Ok here" is printed.

56.

void main()
{
void *v;
int integer=2;
int *i=&integer;
v=i;
printf("%d",(int*)*v);
}
Answer:
Compiler Error. We cannot apply indirection on type void*.
Explanation:
Void pointer is a generic pointer type. No pointer arithmetic can be done on it. Void pointers are normally used for,
1. Passing generic pointers to functions and returning such pointers.
2. As a intermediate pointer type.
3. Used when the exact pointer type will be known at a later point of time.

57.

void main()
{
int i=i++,j=j++,k=k++;
printf(“%d%d%d”,i,j,k);
}
Answer:
Garbage values.
Explanation:
An identifier is available to use in program code from the point of its declaration.
So expressions such as i = i++ are valid statements. The i, j and k are automatic variables and so they contain some garbage value. Garbage in is garbage out (GIGO).

58.

void main()
{
static int i=i++, j=j++, k=k++;
printf(“i = %d j = %d k = %d”, i, j, k);
}
Answer:
i = 1 j = 1 k = 1
Explanation:
Since static variables are initialized to zero by default.

59.

main()
{
while(1)
{
if(printf("%d",printf("%d")))
break;
else
continue;
}
}
Answer:
Garbage values
Explanation:
The inner printf executes first to print some garbage value. The printf returns no of characters printed and this value also cannot be predicted. Still the outer printf prints something and so returns a non-zero value. So it encounters the break statement and comes out of the while statement.

60.

main()
{
unsigned int i=10;
while(i-->=0)
printf("%u ",i);

}
Answer:
10 9 8 7 6 5 4 3 2 1 0 65535 65534…..
Explanation:
Since i is an unsigned integer it can never become negative. So the expression i-- >=0 will always be true, leading to an infinite loop.

61.

main()
{
int x,y=2,z,a;
if(x=y%2) z=2;
a=2;
printf("%d %d ",z,x);
}
Answer:
Garbage-value 0
Explanation:
The value of y%2 is 0. This value is assigned to x. The condition reduces to if (x) or in other words if(0) and so z goes uninitialized.

62.

main()
{
int a[10];
printf("%d",*a+1-*a+3);
}
Answer:
4
Explanation:
*a and -*a cancels out. The result is as simple as 1 + 3 = 4 !

63.
main()
{
unsigned int i=65000;
while(i++!=0);
printf("%d",i);
}
Answer:
1
Explanation:
Note the semicolon after the while statement. When the value of i becomes 0 it comes out of while loop. Due to post-increment on i the value of i while printing is 1.

64.

main()
{
int i=0;
while(+(+i--)!=0)
i-=i++;
printf("%d",i);
}
Answer:
-1
Explanation:
Unary + is the only dummy operator in C. So it has no effect on the expression and now the while loop is, while(i--!=0) which is false and so breaks out of while loop. The value –1 is printed due to the post-decrement operator.

65.

Is the following statement a declaration/definition. Find what does it mean?
int (*x)[10];
Answer
Definition.
x is a pointer to array of(size 10) integers.

66.

#ifdef something
int some=0;
#endif

main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}

Answer:
Compiler error : undefined symbol some
Explanation:
This is a very simple example for conditional compilation. The name something is not already known to the compiler making the declaration int some = 0; effectively removed from the source code.

67.

#if something == 0
int some=0;
#endif

main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}

Answer
0 0
Explanation
This code is to show that preprocessor expressions are not the same as the ordinary expressions. If a name is not known the preprocessor treats it to be equal to zero.

68.
int swap(int *a,int *b)
{
*a=*a+*b;*b=*a-*b;*a=*a-*b;
}
main()
{
int x=10,y=20;
swap(&x,&y);
printf("x= %d y = %d\n",x,y);
}
Answer
x = 20 y = 10
Explanation
This is one way of swapping two values. Simple checking will help understand this.

69.
main()
{
int i=5;
printf("%d",++i++);
}
Answer:
Compiler error: Lvalue required in function main
Explanation:
++i yields an rvalue. For postfix ++ to operate an lvalue is required.

70.

main()
{
char *p = “ayqm”;
char c;
c = ++*p++;
printf(“%c”,c);
}
Answer:
b
Explanation:
There is no difference between the expression ++*(p++) and ++*p++. Parenthesis just works as a visual clue for the reader to see which expression is first evaluated.

71.

main()
{
int i=5;
printf(“%d”,i=++i ==6);
}

Answer:
1
Explanation:
The expression can be treated as i = (++i==6), because == is of higher precedence than = operator. In the inner expression, ++i is equal to 6 yielding true(1). Hence the result.

72.
void ( * abc( int, void ( *def) () ) ) ();

Answer::
abc is a ptr to a function which takes 2 parameters .(a). an integer variable.(b). a ptr to a funtion which returns void. the return type of the function is void.

73.

main()
{
while (strcmp(“some”,”some\0”))
printf(“Strings are not equal\n”);
}
Answer:
No output
Explanation:
Ending the string constant with \0 explicitly makes no difference. So “some” and “some\0” are equivalent. So, strcmp returns 0 (false) hence breaking out of the while loop.

74.

main()
{
char str1[] = {‘s’,’o’,’m’,’e’};
char str2[] = {‘s’,’o’,’m’,’e’,’\0’};
while (strcmp(str1,str2))
printf(“Strings are not equal\n”);
}
Answer:
“Strings are not equal”
“Strings are not equal”
….
Explanation:
If a string constant is initialized explicitly with characters, ‘\0’ is not appended automatically to the string. Since str1 doesn’t have null termination.

75.

main()
{
int i = 3;
for (;i++=0;) printf(“%d”,i);
}

Answer:
Compiler Error: Lvalue required.

76.

void main()
{
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));
printf(“%d”,*mptr);
int *cptr = (int*)calloc(sizeof(int),1);
printf(“%d”,*cptr);
}
Answer:
garbage-value 0
Explanation:
The memory space allocated by malloc is uninitialized, whereas calloc returns the allocated memory space initialized to zeros.

77.

void main()
{
static int i;
while(i<=10) (i>2)?i++:i--;
printf(“%d”, i);
}
Answer:
32767
Explanation:
Since i is static it is initialized to 0. Inside the while loop the conditional operator evaluates to false, executing i--. This continues till the integer value rotates to positive value (32767). The while condition becomes false and hence, comes out of the while loop, printing the i value.