C Interview Questions
C Interview Questions
Stack frame
Let me brief through all the terminologies before we get into the working.
Stack frame – The section of memory where the local variables, arguments, return address and other information
of a function are stored, is called stack frame or activation record.
Stack pointer – For function calls, a bulk of data is pushed and popped from the memory, whenever a function is
invoked and returned respectively. But we may need to access the data which is deep into the stack and it will be
inefficient to pop off all the data to do that. Hence, unlike conventional stack implementation, we have a register
called stack pointer that points to top of the stack such that all the addresses smaller than the address to which the
stack pointer points are considered as garbage and all the address larger are considered as valid.
Stack bottom – It is the highest valid address of the stack. When the stack is initialized the stack pointer points to
stack bottom.
Stack limit – It is the smallest valid address of the stack. When the stack pointer goes below this address, then
there’s stack overflow.
Frame pointer – When a new function is invoked the frame pointer points to where the stack pointer was and when
the function returns the stack pointer points back to where the frame pointer is.
Return address – It points to address (within the caller function) to which the control should pass when the callee
(current) function returns.
Static link – This comes into picture for the programming languages that support nested functions. When a function
(nested function) is defined within another function (enclosing function), the nested function may need to access the
variables of the enclosing function. Therefore, the nested function’s stack frame should be able to access the
enclosing function’s frame. This made possible by static link which points to the address of the enclosing function’s
frame.
How it works?
The working of stack differs with different programming languages. Programming languages like C, doesn’t support
nested functions and they dont need static link. Programming lanuages like Pascal support nested functions and
they use static link. There are programming languages like ML and Scheme which support both nested functions
and function-valued variables (ie., a function returned as a result of another function). I am not aware of how these
function calls work. I have discussed the working only for programming languages that support nested functions.
Consider a pseudo-C code: (This doesn’t work in C. Just using a comfortable syntax.)
int foo (int arg1)
{
int f (int arg2)
{
int i=10;
return arg2 * i;
}
int g(int arg3)
{
return f(arg3);
}
return g(arg1);
}
f and g are nested functions of foo. foo invokes g which inturn invokes f.
Stack frame – working
When the function foo invokes function g, the argument arg3 is pushed into the stack. A new section memory is
allocated for the function g and the stack pointer points to the highest unused address. The frame pointer points to
where stack pointer was. The old frame pointer is pushed ie., 1. The static link which points to the address of the
enclosing function foo is pushed, ie., 1. The return address is pushed ie., to foo.
Then when the function f is invoked the argument arg2 is pushed. Now the frame pointer points to where the stack
pointer was. The old FP is pushed ie., 3. The static link pointing to foo is pushed ie., 1. The return address is
pushed ie., to g. Then the local variable i is pushed.
When the function f returns. The stack pointer points to where stack pointer was and the frame pointer points to the
address stored as old FP in f’s stack frame.
This simply doesn’t work with languages like ML and scheme because in those, the local variables should not be
destroyed while the function returns! as they may be required for the nested callee function.
How recursive functions work?
The recursive functions work in same way as the other functions. For every recursive call a new stack frame of the
function is created. But this avoided in tail recursive calls in functional languages. In tail recursive call, each
recursive call is made to loop to the same stack frame.
Stack overflow
When the stack pointer goes below the stack limit, then there’s stack overflow. The most common cause for stack
overflow is the infinite loop in the recursive function calls. Imagine if a function is invoked recursively for infinite
times, a stack frame gets appended for every recursive call and at one point the stack pointer goes below the stack
limit and thus a stack overflow is caused.
References:
1. Understanding the stack.
2. Modern compiler implementation in ML by Andrew W. Appel
User defined data type is used to create new data types. The new data
types formed from fundamental data types.4 Different user defined data
types are: struct, union, enum, typedef.
Enum- Enum is a user defined datatype which takes values from the
enumerators.
Enumerators is a user defined list of named integer constant.
Syntex-
Enum tag{member1,member2,member3,…}; //I Method
Enum tag{member1,member2,member3,…}var1,var2; //II Method
Eg.
Enum month{Jan,Feb,Mar,…}; //I Method
Result=Jan=0,Feb=1,Mar=2
Enum month{Jan,Feb=5,Mar,…}; //Also possible
Result=Jan=0,Feb=5,Mar=6
3) What is qualifier?
Size Qualifier-1)Signed 2)Unsigned(Asked In BOSCH 20-03-14)
Type Qualifier-1)Const 2)Volatile
You can use Size Qualifiers to indicate what size of number you want to
store inside your datatype.
4) const and volatile qualifier
Const & volatile are type qualifiers.
When we use const qualifier with any of the variable,it means that the
value of that variable cannot be changed by the program directly.
Eg.Const int a=10;
Const float pi=3.14;
• The use of const conveys some very useful information to someone
reading your code. In effect, declaring a parameter const tells the user
about its intended usage.
• const has the potential for generating tighter code by giving the
optimizer some additional information.
• Code that uses const liberally is inherently protected by the compiler
against inadvertent coding constructs that result in parameters being
changed that should not be. In short,they tend to have fewer bugs.
Volatile
When we are using any variable with volatile qualifier, it means that we
are instructing the compiler to turn off the optimization process for
that variable i.e. we are forcing the compiler to read the value of the
variable from the memory only, every time it encounters the program.
multithreading systems.
How???
(It tells the compiler that the object is subject to sudden change for
reasons which cannot be predicted from a study of the program itself, and
forces every reference to such an object to be a genuine reference.)
The reason for having this type qualifier ismainly to do with the
problems that are encountered in real-time or embedded systems
programming using C. Imagine that you are writing code that controls a
hardware device by placing appropriate values in hardware registers at
known absolute addresses.)
9) Program to find x^y using inbuilt function pow() and without using
inbuilt function
//To find the power of the the given no
#include<stdio.h>
int power(int,int);
main()
{
int no,pow;
printf("Enter the no\n");
scanf("%d",&no);
printf("Enter the power you want to find\n");
scanf("%d",&pow);
//printf("Result=%d\n",no^pow); //XOR Symbol
printf("Result=%d\n",power(no,pow));
}
Types-
a)Library Functions(Pre Define)
These functions are present in the C library & are predefined. The source
code of the library functions are not given to the user. These functions
are pre compiled & the user gets only the object code. The object code of
the library fun() is linked to the object code of the progm by the
linker.
Fn() Definition- Predefined, precompiled& present in the library.
Fn() Declaration- In the header files (files with a .h extension)
Fn() Call- By the programmer.
Eg. Printf() is defined in the stdio.h.
Eg.
a)auto
All the variables declared inside the block without any storage class are
considered as auto variables. We can also use auto storage class with
them. Automatic variable comes into the existence each time the function
is executed & are destroyed when the function terminates.
1-Lifetime- Function/Block
2-Scope- Function/Block
3-Initial value- Garbage
4-Place of Storage- Memory(Stack)
d)register
A register storage class is applied to the automatic variables only.
Thescope, lifetime& initial value of register variables is same as that
of the automatic variables.The only difference is that automatic
variables are stored in the memory while the register variables are
stored in the
CPU register.
We cannot use address operator (&) with that variables.Thus we cannot
scan the register variable.
Since the no. of the registers in the CPU are limited thus we can use
only limited no. of register variables.We can specify register class only
for int,char & pointer types.
If the variable other than these types is declared as register variable,
the compiler will not show error but it will considered those variables
as auto variable.
The register storage can be applied to the formal arguments of the
functions while other storage classes cannot be used.
1-Lifetime- Function/Block
2-Scope- Function/Block
3-Initial value- Garbage
4-Place of Storage- Register
1-Lifetime- Program
2-Scope- Declaration to the end of the file/Function
3-Initial value- Zero
4-Place of Storage- Memory (data area)
ii)Global static
The main purpose of using the static storage class with the global
variable is information hiding. If aglobal(external) variable is used
with the static storage class then it cannot be accessed by the other
files.
1-Lifetime- Program
2-Scope- Declaration to the end of the file/Function
3-Initial value- Zero
4-Place of Storage- Memory (data area)
The data segment is a fixed-size area in memory used for static & extern
variables. The data segment is subdivided into two parts, one for
initialized variables and another for uninitialized variables.
The stack is an area of memory that starts out small and grows
automatically up to some predefined limit.
The third and final area doesn’t actually store variables but can be used
to store data pointed by variables.
Pointer variables that are assigned to the result of a call to the
malloc() function contain the address of a dynamically allocated area of
memory. This memory is in an area called the “heap.”
The heap is another area that starts out small and grows, but it grows
only when the programmer explicitly calls malloc() or other memory
allocation functions, such as calloc(). The heap can share a memory
segment with either the data segment or the stack, or it can have its own
segment. It all depends on the compiler options and operating system. The
heap, like the stack, has a limit on how much it can grow, and the same
rules apply as to how that limit is determined.
In
const int *p;
The value stored in the * will be constant. But the pointer can point to
any value & that value will become const.
In
const int *const p;
The pointer is constant as well as the value pointed by the variable is
also constant.
15) An array is defined in p1.c and can u use extern int arr[] in another
program p2.c
Yes,then the previous used array will be available for this file also.
16) How to modify value in 'a' in const int a=5 without using pointers.
17) Swap two variables without using third variable (two ways)
Int a=10,b=20;
I) B=a+b-(a=b);
II) b=a^b;
A=a^b;
B=a^b;
The use of the structures are in making database like single linked list
(symbol table),in the designing of the OS,etc.
The use of the union in protocol designing,semaphore,etc.
The other main difference between the structure & union is that we cannot
initialize all the members of the union simultaneously.
2)
#define student struct stu \
{ \
Int rollno; \
Char name[20]; \
Float marks; \
} \
Student a;
Loading:
Loading is bringing the executable code into the main memory
forexecution. The header record is checked to verify that there correct
program is been presented for loading. As each text record is read, the
object code it contains is moved to the indicated address in memory. When
the end record in encountered, the loader jumps to the specified address
to begin the execution of the loaded program.
Dynamic library:
1- Done by dynamic linking.
2- Also known as shared objects.
3- Creates smaller binary file.
4- Dependent of libraries at runtime.
33) Write a program to find the middle node in a single linked list using
only one for loop
34) Write a program to implement double linked list using only one
pointer(Hint: use exor operator)
38)What is thread?
A thread is a basic unit of CPU Utilization. It comprises of a thread
ID,a PC,a register set & a stack. If different threads belongs to the
same process then they will also share its code section & other CPU
resources.
A traditional process has a single thread of control.
If a process has multiple thread of control, it can perform more than one
task at a time.
Types-
User Thread-The support for the user thread is provided at user level
without kernel support.
Kernel Thread-The support for the kernel thread is provided at kernel
level. These are supported & managed directly by OS.
User threads are easy to createand use but the disadvantage is that if
they perform a blocking system calls the kernel is engaged completely
tothe single user thread blocking other processes.
They are created in user space.Kernel threads are supported directly by
the operating system.
They are slower to create and manage. Most of the OS like Windows NT,
Windows 2000, Solaris2, BeOS, and Tru64 Unixsupport kernel threading.
Which protocol is synchronous & full duplex in between I2C & SPI?
SPI = synchronous, full duplex
I2C= synchronous
What is a macro?
A macro is a fragment of code which has been given a name. Whenever the
name is used, it is replaced by the contents of the macro. There are two
kinds of macros-
i)Object-like macros resemble data objects when used,
ii)function-like macros resemble function calls.
2.Inline functions are specified using the same syntax as any other
function except that they include the inline keyword in the function
declaration.
4. Macro never returns a value but inline may return depending upon its
prototype.
5. Inline function are parsed by the compiler, whereas the #define are
expanded in the preprocessor stage.
7. Macro doesn’t make the part of code segment but inline function does.
UDP:
1-Connection less protocol
2-unreliable
3-Best effort delivery but no guarantee
4-No error Detection
5-Fast
6-No Windowing???
You are in home. But you need to access the office server router. How can
you do that?
By using "Telnet"
By using "Telnet" or "SSH"
Virtual private n/w
If you have public ip, then you can access from your home.But you have a
net connection first.
What are the differences among router, switch, bridge and hub?
All of them are devices and are used in network. Their differences are:
*Router: Layer 3 device, can work on physical, data and network layer.
*Switch: Layer 2 device, can work on data link layer
*Bridge: Layer 2 device, can work on data link layer.
*Hub: Layer 1device, just a multi-port repeater and works on physical
layer
Mark one of the most important difference between TCP and UDP.
TCP is a connection-oriented and UDP is a connection-less protocol
Stack is a memory in which all the local auto variables & formal
arguments are stored&it also stores the function call address.
Theideaisasfollows:Theoperatingsystemkeepsseveraljobsinmemory
Simultaneously(Figure1.7)
.Thissetofjobscanbeasubsetofthejobskeptinthejobpool—
whichcontainsalljobsthatenterthesystem—sincethenumber
ofjobsthatcanbekeptsimultaneouslyinmemoryisusuallysmallerthan
thenumberofjobsthatcanbekeptinthejobpool.Theoperatingsystem
picksandbeginstoexecuteoneofthejobsinmemory.Eventually,thejob may have to
wait forsometask,suchasanI/Ooperation,tocomplete.Inanon-multi programmed
system, the CPUwoulditidle.Inamultiprogrammed
system,theoperatingsystemsimplyswitchesto,andexecutes,another job. When
that job needs to wait, the CPUisswitchedtoanotherjob,andsoon.
Multiprogrammedsystemsprovideanenvironmentinwhichthevarious
System resources(forexample,CPU,memory,andperipheraldevices)are
utilizedeffectively,buttheydonotprovideforuserinteractionwiththe
computersystem.Timesharing(ormultitasking)isalogicalextensionof
multiprogramming. In time- sharing systems, the CPUexecutesmultiplejobs
byswitchingamongthem, but the switchesoccursofrequentlythattheusers
caninteractwitheachprogramwhileitisrunning.
What is process?
Aprogramloadedintomemoryandexecutingiscalledaprocess.
What is the advantage of virtual memory?
Inatime-sharingsystem,theoperatingsystemmustensurereasonable
responsetime,whichissometimesaccomplished throughswapping,where
processesareswappedinandoutofmainmemorytothedisk.Amorecommon
methodforachievingthisgoalisvirtualmemory,atechniquethatallows
theexecutionofaprocessthatisnotcompletelyinmemory(Chapter9).
Themainadvantageofthevirtual-memoryschemeisthatitenablesusers to
runprogramsthatarelargerthanactualphysicalmemory.
What is the difference between the signed & unsigned int? What is the
range limit of both? (Asked in Brigosha Technologies)
The signed & unsigned keywords can be applied to char & integer
datatypes.
(We cannot use it with float, it will give error=>Tested)
When the keyword unsigned is used the number is always positive & when
the keyword signed is used the number is positive or negative.If the sign
keyword is not defined then by default the variable will be signed.
The range of values for signed datatypes is less than that of unsigned
datatype. This is because in signed datatype, the leftmost bit(MSB) is
used to represent the sign,while in unsigned type this bit is also used
to represent the value.
Type Conversion-
1-Implicit Type Conversion
a- Automatic Type Conversion
i- Automatic Unary Conversion
ii- AutomaticBinary Conversion
b- Type Conversion in Assignment
What is call by value & call by reference? What is the effect of both on
the stack size?
In how many parts the file management divides the hard disk?
File management divides the hard disk into 4 parts (BSID)-
1) Boot Block- OS is present in this block. All booting related
information is present in this block.
2) Super Block- It consists of file system information.
3) Inode Block- It consists of all file information.
4) Data Block- It consists of all files.
What is IPC? Explain its types & also their advantages & disadvantages.
IPC stands for Inter Process Communication.
Generally we have 4 types of IPC.
a) PIPE (Unnamed Pipe)
b) FIFO (Named Pipe)
c) Message Queue
d) Shared Memory
Disadvantage=1. Slowest IPC since kernel have to manage the large data
structure & its different task like, managing the message queue,
searching the desired message.
Advantage=1.Fastest IPC.
Disadvantage=
What is semaphore?
It is a synchronization method so that multiple processes cant access
shared resource at a time. It is a small integer value which is present
in the kernel space used for synchronization between the multiple
processes when the processes are trying to access the shared resource.
Types- a)Mutex b)Normal Semaphore.
Mutex Semaphore (Mutually Exclusive Event) The process which locks the
key have the authority to unlock the key also.
Normal Semaphore If one process locked the key other process has
authority to unlock the key also.
Using semaphore we cannot exchange the data between the two processes.
What is the range of the temp sensor you have used?(Asked in BOSCH 20-03-
14)
-50oC to +150oC
What will be the minimum & maximum voltage reading at that minimum
&maximum temperature?(Asked in BOSCH 20-03-14)
Why you haven’t used thermometer to measure the temp of the room?(Asked
in BOSCH 20-03-14)
(They just want to listen that thermometer (we use to measure the temp of
body) is not having negative temp scale)
What are the criteria on which you have selected the temperature sensor?
(Asked in BOSCH 20-03-14)
1-Range
LM35=-50oC to +150oC
LM35C=-40oC to +110oC
LM35D=0oC to +100oC
2-Calibrated directly in oC-While some of the temperature sensors are
calibrated to oKelvin scale.
3-It draws very less current of 60 microA.
4-Low self-heating(<0.1oC in still air).
5-Linear output.
What are the criteria on which you have selected the RTC?
1-It can be able to show sec, min, hour, date, month, day, year/leap year
& valid up to 2100.
2-Consumes less than 500nA current.
3-Working temp range= -40oC to 85oC.
5-Low power required.
6-Built in battery.
Why you have chosen the SPI protocol for interfacing the ADC MCP3204?
It is having following advantages-
1- It provides arbitrary choice of message size, content & purpose
i.e. it is not limited to 8 bits words. Since our ADC is having 12
bit of resolution.(Main point to use in our project)
2- Requires lower power than I2C.
Power required by I2C=
Power required by SPI=
I2C draws more power than other serial communication buses due to open
drain topology of the communication lines.
3- Slaves use the master’s clock, & don’t need precision oscillators.
4- Slave don’t need a unique address – unlike I2C.
5- Uses only 4 wires which is less than wires used in the parallel
interfaces. (Main point to use in our project)
6- Only a signal is required to select the slave (chip select).
(Main point to use in our project).
7- Full duplex communication.
8- With only a single SPI slave, you *might* not need the CS. (Main
point to use in our project).
9- For single-direction SPI , you *might * only need one of
MOSI or MISO; (Main point to use in our project).
If you only have one SPI slave (e.g. a high speed ADC or DAC), you
can’t ie the device's CS to active and use the SCLK to trigger the
slave to output data (MISO) or to receive data (MOSI ).
Disadvantages-
1- Requires more pins as compares to I2C.
2- No hardware flow control???
3- No hardware slave acknowledgement unlike I2C.
4- Supports only one master device.
5- Only handles short distances compared to RS-232, RS-485 & CAN BUS.
Why you have chosen the I2C protocol for interfacing the RTC DS1307?
Advantages-
1- It is only 2 wire protocol.
2- If your system needs to access multiple devices on a relatively
slow frequency eg. In terms of hundreds or thousands of msec, or
requires multiple masters to access one or more slave devices, I2C
is the choice. If your system only needs to access one high speed
slave device, SPI is a better choice.
3- Flexible data transmission rates.
4- Each device on the bus is independently addressable.
5- Numbers of slaves can be connected according to the addressing
scheme used.
Disadvantages-
1- Slaves of the same address are not possible.
2- Speed is quite slower as compare to SPI.
3- The shared nature of the I2C bus can result in the entire bus
hanging when a single device on the bus stops operating.
4- Use more power than SPI.
What are the differences between UART & USART? (Asteria Aerospace)
USART chips have synchronous & asynchronous modes.In synchronous
transmission,the clock data is recovered separately from the data stream
& no start/stop bits are used. This improves the efficiency of the
transmission on suitable channels since more of the bits sent are usable
data & not character framing. An asynchronous transmission sends no
characters over the interconnection when the transmitting device has
nothing to send,but a synchronous interface must send “pad” characters to
maintain synchronization between the receiver& transmitter. The usual
filler is ASCII “SYN” character. This may be done automatically by the
transmitting device.
What is deadlock?
A deadlock is a situation in which two or more competing actions are each
waiting for the other to finish & thus neither ever does.Deadlock is a
cyclic wait among a set of processes.
In an OS, a deadlock is a situation which occurs when a process or thread
enters a waiting state because a resource requested by it is being held
by another waiting process, which in turn is waiting for another
resource. If a process is unable to change its state indefinitely because
the resources requested by it are being used by another waiting process,
then the system is said to be in deadlock.
Deadlock is a common problem in multiprocessing system, parallel
computing & distributed system, where software & hardware locks are used
to handle shared resources & implement process synchronization.
VI.1: What is the difference between a string copy (strcpy) and a memory
copy (memcpy)? When should each be used?
Answer:
The strcpy()function is designed to work exclusively with strings. It
copies each byte of the source string to the destination string and stops
when the terminating null character(\0) has been moved. On the other
hand, the memcpy()function is designed to work with any type of data.
Because not all data ends with a null character, you must provide the
memcpy()function with the numberof bytes you want to copy from the source
to the destination. The following program shows examples of boththe
strcpy()and the memcpy()functions:
#include <stdio.h>
#include <string.h>
typedef struct cust_str {
int id;
char last_name[20];
char first_name[15];
} CUSTREC;
void main(void);
void main(void)
{
char* src_string = “This is the source string”;
char dest_string[50];
CUSTRECsrc_cust;
CUSTRECdest_cust;
printf(“Hello! I’m going to copy src_string into dest_string!\n”);
/* Copy src_string into dest_string. Notice that the destination
string is the first argument. Notice also that the strcpy()
function returns a pointer to the destination string. */
printf(“Done! dest_string is: %s\n”,
strcpy(dest_string, src_string));
printf(“Encore! Let’s copy one CUSTREC to another.\n”);
printf(“I’ll copy src_cust into dest_cust.\n”);
/* First, initialize the src_cust data members. */
src_cust.id = 1;
strcpy(src_cust.last_name, “Strahan”);
strcpy(src_cust.first_name, “Troy”);
/* Now, use the memcpy() function to copy the src_cust structure to
the dest_cust structure. Notice that, just as with strcpy(), the
destination comes first. */
memcpy(&dest_cust, &src_cust, sizeof(CUSTREC));
printf(“Done! I just copied customer number #%d (%s %s).”,
dest_cust.id, dest_cust.first_name, dest_cust.last_name);
}
When dealing with strings, you generally should use the strcpy()function,
because it is easier to use with strings. When dealing with abstract data
other than strings (such as structures), you should use the memcpy()
function.
VII.24: What is a “null pointer assignment” error? What are bus errors,
memory faults, and core dumps?
Answer:
VII.25: How can you determine the size of an allocated portion of memory?
Answer:
You can’t
VIII.7: Is it possible to execute code even after the program exits the
main()function?