Tuesday, 10 December 2013

HDMI(High Definition Multimedia Interface)

 

HDMI stands for High Definition Multimedia Interface. A HDMI cable is a single cable that serves as link for audio as well as video applications. For a video recorded in high definition, a standard Audio-video component cable gives an output of 480 pixels per inch. On the other hand, HDMI connectors give at least a 720 pixel/inch output, thus giving a more rich and lively video that can recreate the actual scene with more accuracy. There are similar enhancements in audio side too (2.1 channel sound and above). This means that a single HDMI cable can replace up to 11 analog signal cables not only in aspects like reduced clutter, but in bandwidth, content transmission and presentation quality too. HDMI is constantly worked upon and improved by HDMI Consortium, which also handles certifying HDMI cables.

Friday, 6 December 2013

Wi-Fi SD card and USB drive reader


Wi-Fi SD card and USB drive reader




Elecom is going to release the SD card and USB drive reader MR-WI01BK in early December.

The MR-WI01BK is compatible with Wi-Fi connection (IEEE802.11n/g/b). By setting an SD memory card or USB drive to the reader, you can check data or play music saved in those media wirelessly with your smartphone or tablet. This, in effect, allows you to increase the media available to you beyond the smartphone or tablet’s capacity shortage.

It’s able to be accessed by a maximum of 5 devices at a time so that it makes data share with your friends easier.

21 kinds of media are compatible with the card reader MR-WI01BK (5 more kinds can be compatible if you use a conversion adapter).

Your Next USB Connector Will Be Thinner, Reversible


Usb3


As mobile devices get increasingly slimmer, so too will their corresponding USB connectors. Even better, you won't have to flip the cable when you try to slip it in upside down. Finally.

Development for the next-generation USB connector, called the Type-C, is underway and will be thinner and sleeker than current USB 3.0 cables (pictured above), according to the USB 3.1 Promoter Group, which is made up of industry heavy hitters including Microsoft, Hewlett-Packard and Intel.

To pack the powerful punch of the USB 3.1 standard, which can move data at 10 gigabits per second, into a smaller cable, it will closely resemble the USB 2.0 Micro-B. But it has a few advantages over existing models: Specifically, it's reversible, meaning users no longer need to worry about plug orientation.


The plug design is similar to the Apple's Lightning cables and will take away one of USB's main frustrations. The downside is that the new cables won't work with existing connectors.

The Type-C connector is built on existing USB 3.1 and USB 2.0 technologies and will have scalable power capabilities, meaning it will be able to charge a wide range of gadgets.

“While USB technology is well established as the favored choice for connecting and powering devices, we recognize the need to develop a new connector to meet evolving design trends in terms of size and usability,” said Brad Saunders, USB 3.0 Promoter Group Chairman, in a statement. “The new Type-C connector will fit well with the market’s direction and affords an opportunity to lay a foundation for future versions of USB.”

Friday, 29 November 2013

Latency Tolerence Messaging in USB

USB: Enable Latency Tolerance Messaging (LTM):

USB 3.0 devices may optionally support a new feature called Latency Tolerance Messaging.  If both the xHCI host controller and the device

support LTM, it should be turned on in order to give the system hardware a better clue about the latency tolerance values of its PCI devices.

Once a Set Feature request to enable LTM is received, the USB 3.0 device will begin to send LTM updates as its buffers fill or empty, and it can tolerate more or less latency.

The USB 3.0 spec says that LTM should be disabled just before the device is placed into suspend.  Then the device will send an updated LTM notification.

So that the system doesn't think it should remain in an active state in order to satisfy the latency requirements of the suspended device.

The Set and Clear Feature LTM enable command can only be sent to a configured device.  The device will respond with an error if that command is sent while it is in the Default or Addressed state.

Make sure to check the status of LTM. LTM should be enabled once a new configuration.  If we end up sending duplicate Set Feature LTM Enable commands on a switch from one installed configuration to another

configuration, that should be harmless. Make sure that LTM is disabled before the device is unconfigured. If no drivers are bound to the device, it doesn't

make sense to allow the device to control the latency tolerance of the xHCI host controller.

USB 3.0 ARCHITECTURE

USB 3.0 ARCHITECTURE:

Physical Layer:

        The physical layer defines the PHY portion of a port and physical connection between the Host and Device.

The physical connection consist of two differencial data pairs with signalling rate 5Gbps.

In electrical aspects the path are characterised as a Transmitter,Channel and Receiver.

In electrical level each differencial link is initialised by enablink its receiver termination.

The transmitter is responsible for detecting the far end device information as an indication of a bus connection and informing the link layer so the connect status can be factored into link operation and management.

USB 3.0 cables have separate shielded differential pairs of lines for transmitting and receiving data. These lines exist along with the USB 2.0 signals.

Thus, a USB 3.0 cable contains a total of 9 pins, including the 4 pins which are part of USB 2.0 cable. The maximum length of a USB 3.0 cable is limited to 3 meters due to the high signaling rate that it supports.

As for the power distribution by the USB 3.0 host, 150mA is considered as the unit load. The USB 3.0 host supplies 1 unit load of current for unconfigured devices and 6 unit loads of current for configured devices.

The USB 3.0 host detects the device connection based on the receiver end termination, and the transmitter is responsible for doing this action. USB 3.0 uses spread spectrum clocking on its signaling.

Spread spectrum clocking spreads the energy of the signal over a larger frequency band rather than concentrating it over a small frequency band at a high level. This helps to reduce EMI emissions.

The USB 3.0 physical layer supports Low Frequency Periodic Signaling (LFPS) which is used to manage signal initiation and low power management on the bus to consume less power on an idle link.


Link layer:

The link layer is responsible for maintaining a reliable and robust communication channel between the host and device. The Link Training and Status State Machine (LTSSM) is the core of the USB 3.0 link layer and defines link connectivity and link power management states and transitions.

 LTSSM consists of 12 states:

 Four link power states for better power management:
       
    U0 – normal operational mode
       
    U1 – Link idle with fast exit (PLL remains on)
       
    U2 – Link idle with slow exit (PLL may be off)
       
    U3 – Suspend
       
    U1, U2, U3 have increasingly longer wakeup times than U0, and thus allow transmitters to go into increasingly deeper sleep.
   
    Four link initialization and training states (Rx.Detect, Polling, Recovery, Hot Reset).
   
    Two link test states (Loopback and Compliance Mode).
   
    SS.Inactive (link error state where USB 3.0 is non-operable).

        SS.Disabled (SuperSpeed bus is disabled and operates as USB 2.0 only).

Link commands are used to maintain the link flow control and to initiate the change in link power state.


Protocol layer:

The protocol layer defines the communication rules between a host and device. USB 2.0 transactions consist of 3 packets: token, data, and handshake.

A transaction is initiated with the token packet and this is always from the host. Data packets deliver the payload data and can be sourced by the host or device. Handshake packets acknowledge the error-free receipt of data and are sent by the receiver of data.

In the case of SuperSpeed, however, to save bandwidth the token is incorporated into the data packet for OUT transactions. The token is replaced by the handshake for IN transactions; i.e., an ACK packet acknowledges the previous data packet that has been sent and requests the next data packet.

USB 3.0 packets are routed to the specific device with the help of the route string in the packet header. USB 3.0 does not poll for the readiness of the devices. If a device responds with “NRDY” (Not Ready) to an IN Transaction Packet (TP) from the host, then the host stops talking to that device until the device sends the “ERDY” (ready) packet saying that now it is ready to transmit the data.

USB 3.0 supports transmitting data in bursts (multiple data packets) without receiving an acknowledgement. The protocol allows efficient bus utilization by concurrently transmitting and receiving over the bus. A transmitter (host or device) can burst multiple packets of data back-to-back while the receiver can transmit data acknowledgements without interrupting the burst of data packets.

Also, the host may simultaneously schedule multiple OUT bursts to be active at the same time as IN bursts.

USB 3.0 has enhanced the bulk capabilities of USB 2.0 by adding a protocol called “Stream”. This allows you to accept multiple commands on a pipe from the host, and allows you to complete them out of order using the stream IDs.

USB 3.0 INTRODUCTION

USB 3.0:

Universal Serial Bus 3.0 (USB 3.0) is a hardware communication interface used to connect peripheral devices to a computer. It is the third generation of the USB interface developed in 2008 and standardized by USB Implementers Forum (USB-IF).

The USB 3.0 interface provides a faster data transfer rate (DTR) than previous USB versions. USB 3.0 uses a dual-bus structural design, whereas earlier versions use a serial interface.

The USB 3.0 also replaces device polling (checking connections or determining the need to communicate) with an interrupt architecture protocol.USB 3.0 is also known as SuperSpeed USB.

A USB 3.0 device may be plugged into a USB socket and used as a USB power supply for direct current (DC) in connecting portable devices.

Compared to older USB versions, the USB 3.0 provides various features:

        1.Higher DTR of up to 5 Gbps
   
    2.Decreased power consumption
  
    3.Higher speed connectors and cables
   
    4.Backward compatible with USB 2.0
   
    5.Better power management structure
   
    6.Support of bulk and isochronous transfers
   
    7.Up to 80 percent more power with configured devices
   
    8.Up to 50 percent more power with non-configured devices
   
    9.Replaces device polling with interrupt architecture protocol
   
    10.Supports full-duplex data transfer using dual-bus architecture
   
    11.Supports a a power savings mode when idle (by either the computer or a device)

The USB 3.0 has 4-pin architecture, versus earlier versions. The USB 3.0 Type A plugs and sockets are backward compatible with USB 2.0, but USB 3.0 Type B plugs do not accept earlier socket versions.

The USB 3.0 was designed to increase power input, decrease power consumption and increase DTR speed. Currently, the USB 3.0 standard supports a DTR of up to 5 Gbps. Typically, the throughput is 4 Gbps, and the USB-IF considers a DTR of 3.2 Gbps attainable.

USB 3.0 have 8 primary conductors.Three usb twisted pair for USB data paths(D+,D-,SSTX+,SSTX-,SSRX+,SSRX-,GND,VBUS).

The power management of USB 3.0 is same as that of USB2.0 and Power distribution over the USB 3.0 deals with the issue of how USB devices consume power for downstream ports to which they are connected,It is similar to USB2.0 with increased suuply for device operating at super speed.

Earlier versions of USB used a device polling method, in which the host controller periodically looks for active data traffic. USB 3.0 replaced this method with an interrupt-based protocol, in which the devices “interrupt” the host by sending it a signal to begin data transfer.

This prevents any connected but non-active or idle devices (those not being charged by the USB port) from causing power drain by the host controller as it continually “polls” for data traffic.

Legacy 2.0 devices will benefit from this feature as well, as it is backward compatible with USB 2.0 certified devices.

Not only does USB 3.0 deliver a welcome increase in data transfer speed, it carries a heftier punch of power as well. USB 2.0 is unable to provide enough power for many devices, requiring these peripherals to use either two USB ports or their own power source in addition to the one USB connection.

USB 3.0 addresses this need with a substantial boost in its power output that will enable users to power and charge more devices, more quickly. This specification is often cited in general terms as an increase from USB 2.0’s 500 mA output to the 900 mA USB 3.0 specification.

This increase in current will also enable USB hubs to support more peripherals as well as allow even more power-hungry devices to charge via USB. so the most battery powered devices will also charge faster. 

USB 3.0 products and applications:

As the transition to USB 3.0 continues, many 2.0 devices will continue to be successfully deployed, taking advantage of the backward compatibility of the interface as the market moves toward mainstream adoption of USB 3.0.

Topping the list of applications best served by USB 3.0 are high-bandwidth devices that

currently challenge the throughput capabilities of USB 2.0, including:

    1.External hard drives (2–3 times faster than USB 2.0 predecessors)

    2.High-resolution webcams and video surveillance cameras

    3.Video display solutions

    4.Digital video cameras and digital still cameras

    5.Multi-channel audio interfaces

    6.External media such as Blu-ray drives

    7.High-end flash drives, particularly when multiple devices are attached via one USB hub

Monday, 4 November 2013

DIFFERENCE BETWEEN MSC VS MTP

MSC(Mass Storage Class)

    MSC, Mass Storage Class, is the mode originally used on devices such as external hard drives, CD and DVD drives, flash memory drivers, gaming systems, digital cameras and music devices connected to your USB port.

MTP(Media Transfer Protocol)

    MTP, Medial Transfer Protocol, was developed by Microsoft and is also used to transfer data between your computer and devices connected to it.

MTP:

1. Can copy files over  and then access on them on the device without mounting/unmounting

2. File transfer is available immediately when plugged in without having to mount

3.while in MTP mode we can use other functions of the Mobile Device.

4.No limitations for file size to be transfered.

Mass storage Class:

1. Better security since you have to get past the lock screen to mount

2. Is actually a real drive in Windows, so you can do all operations normally

3.While in MSC Mode we cannot use other functions of the mobile device.

4.Limitations for File size to be transfered-Only 4GB in size can be transfered.

Thursday, 24 October 2013

COMPILER DESIGN

Compiler Design:
       
        A Compiler is a computer program that transform source code written in a programming language into another computer language.The reason for wanting transform source code is to create an Executable program.

Structure Of a Compiler:

Compilers bridge source programs in high-level languages with the underlying hardware.

A compiler requires

     1. determining the correctness of the syntax of programs.

     2. generating correct and efficient object code.

     3. run-time organization.

     4. formatting output according to assembler and/or linker conventions.

 A compiler consists of three main parts:

        The frontend

        The middle-end

        The backend.
   
             The Front end checks whether the program is correctly written in terms of the programming language syntax and semantics. Here legal and illegal programs are recognized. Errors are reported, if any, in a useful way. Type checking is also performed by collecting type information.The frontend then generates an intermediate representation or IR of the source code for processing by the middle-end.

             The Middle end is where optimization takes place. Typical transformations for optimization are removal of useless or unreachable code, discovery and propagation of constant values, relocation of computation to a less frequently executed place (e.g., out of a loop), or specialization of computation based on the context. The middle-end generates another IR for the following backend. Most optimization efforts are focused on this part.

              The Back end is responsible for translating the IR from the middle-end into assembly code. The target instructions are chosen for each IR instruction.
Register allocation assigns processor registers for the program variables where possible. The backend utilizes the hardware by figuring out how to keep parallel execution units busy, filling delay slots, and so on. Although most algorithms for optimization are in NP, heuristic techniques are well-developed.

There are two major parts of a compiler:

         1.Analysis 

        2.Synthesis

In analysis phase, an intermediate representation is created from the given source program.

Lexical Analyzer, Syntax Analyzer and Semantic Analyzer are the parts of this phase.

In synthesis phase, the equivalent target program is created from this intermediate representation.

Intermediate Code Generator, Code Generator, and Code Optimizer are the parts of this phase.


PARSER:

    In computer technology, a parser is a program, usually part of a compiler, that receives input in the form of sequential source program instructions, interactive online commands, markup tags, or some other defined interface and breaks them up into parts (for example, the nouns (objects), verbs (methods), and their attributes or options) that can then be managed by other programming (for example, other components in a compiler).

 A parser may also check to see that all input has been provided that is necessary.

Lexical Analysis:

        It is a Process of converting sequence of characters into sequence of Tokens.

Syntactic Analysis:

        The process of analyzing a sequence of tokens to determine its grammatical structure.

Syntax errors are identified during this stage.

Symantic analysis:

        The Process of analyzing semantic cheeks(ex:Type checking,Object Binding).

Compiler Optimization:

        This Process tune the output of a compiler to minimize or maximize some attributes of an executable computer program.

Code generator:
        It will convert the intermediate files into assembly language programs.





                           

Wednesday, 25 September 2013

SORTING TECHNIQUES

SORTING ALGORITHMS

Sorting is the process that organizes the collection of data either in ascending or descending order.

there will be two sorting process.They are

   1.Internal sorting
   2.External sorting

Internal sorting:
  Internal sorting is the process in which sorting is to be done within the computer's memory.
  External sorting needs externa memory such as HardDisks for sorting process.

There are many sorting algorithms:

  1.Insertion sort
  2.Selection sort
  3.Bubble sort
  4.Merge sort
  5.Quick sort

Selection sort:
In the list is divided into two sublists, sorted and unsorted.

We find the smallest element from the unsorted sublist and swap it with the element at the beginning of the unsorted data.

Each time we move one element from the unsorted sublist to the sorted sublist, we say that we have completed a sort pass.

A list of n elements requires n-1 passes to completely rearrange the data.

A list of n elements require n-1 passes to arranging the data. 


Bubble sort:

In the list is divided into two sublists, sorted and unsorted.

The smallest element is bubbled from the unsorted list and move the element at the beginning of the sorted sublist.

Each time we move one element from the unsorted list to the sorted sublist, we say that we have completed a sort pass.

A list of n elements requires n-1 passes to completely rearrange the data.

A list of n elements require n-1 passes to arranging the data. 

 

comparision:

Selection sort:
Worst scenario: O(n2);
Average scenario: O(n2);
Best scenario: O(n2);

Bubble sort:
Worst scenario: O(n2);
Average scenario: O(n2);
Best scenario: O(n2);

Modified Bubble sort:

Worst scenario: O(n2);
Average scenario: O(n);
Best scenario: O(n);

The selection sort and bubble sort performance wise both are same.But the method of sorting is different with each other.

The difference between the bubble sort and modified bubble sort is modified bubble sor tis decreasing the number of steps used for sorted process.

Insertion sort.

In this method, sorting is done by inserting elements into an existing sorted list.
Initially, the sorted list has only one element.
Other elements are gradually added into the list in the proper position.

Merge Sort:

Merge sort is one of the Sorting Technique which is based on divide and conquer mechanism.

In this method,initially then given  elements are partially divided,and again they divided using recursive method.

After partioning of elements the first half and second half of the elements sorted seperatedly and then they have merged together.


Application of Merge Sort:

1.It can handle large amount of data and process it quickly.

2.It is also used to merge the two sorted lists.

Quick sort:

Quick sort is a most efficient algorithm as compared to selection or bubble sort.

It works by first of all by partitioning the array around a pivot value and then dealing with the 2 smaller partitions separately.

 

Partitioning is the most complex part of quick sort.

The simplest thing is to use the first value in the array,  as the pivot.

After the partitioning, all values to the left of the pivot are <= pivot

and all values to the right are > pivot.This gives better performance.

The approach of Quick sort is called Depth fast approach.


Best case running time of quick sot is O(n log2 n).

Worst case is O(n2).

Booting:

    Booting is a process or set of operations that loads and hence starts the operating system, starting from the point when user switches on the power button.


Boot Loader:

    A boot loader is a type of program that loads and starts the boot time tasks and processes of an operating system or the computer system.

It enables loading the operating system within the computer memory when a computer is started or booted up.

A boot loader is also known as a boot manager.

Booting Sequence:
       
Boot sequence is the order in which a computer searches for nonvolatile data storage devices containing program code to load the operating system .

Typically, a Macintosh structure uses ROM and Windows uses BIOS to start the boot sequence.

Once the instructions are found, the CPU takes control and loads the OS into system memory.

The devices that are usually listed as boot order options in the BIOS settings are hard disks, floppy drives, optical drives, flash drives, etc.

The user is able to change the boot sequence via the CMOS setup. Boot sequence is also called as boot order or BIOS boot order.

The Booting Sequence is Follows:

   
     Turn on the Power button.
        
    CPU pins are reset and registers are set to specific value.
        
     CPU jump to address of BIOS (0xFFFF0).
        
     BIOS run POST (Power-On Self Test) and other necessary checks.
        
     BIOS jumps to MBR(Master Boot Record).
        
     Primary Bootloader runs from MBR and jumps to Secondary Bootloader.
        
     Secondary Bootloaders loads Operating System.

These are the tasks that are carried during booting process.

BOOTSTRAPPING

BOOT STRAP:

    Bootstrap is the process of loading a set of instructions when a computer is first turned on or booted.

During the start-up process, diagnostic tests are performed, such as the power-on self-test (POST), that set or check configurations for devices and implement routine testing for the connection of peripherals, hardware and external memory devices.

The boot loader or bootstrap program is then loaded to initialize the OS.

Typical programs that load the OS are:

    GNU grand unified bootloader (GRUB): A multiboot specification that allows the user to choose one of several OSs
   

    NT loader (NTLDR): A boot loader for Microsoft’s Windows NT OS that usually runs from the hard drive


    Linux loader (LILO): A boot loader for Linux that generally runs from a hard drive or floppy disc


    Network interface controller (NIC): Uses a boot-loader that supports booting from a network interface such as Ether-boot or pre-boot execution environment (PXE)


Prior to bootstrap a computer is said to start with a blank main memory and an intact magnetic core memory or kernel.

The bootstrap allows the sequence of programs to load in order to initiate the OS.

The OS is the main program that manages all programs that run on a computer and performs tasks such as controlling peripheral devices like a disc drive, managing directories and files, transmitting output signals to a monitor and identifying input signals from a keyboard.

Bootstrap can also refer to as preparing early programming environments incrementally to create more complex and user-friendly programming environments.
   

Monday, 16 September 2013

CONTEXT SWITCHING

CONTEXT SWITCHING:
   
A Context switch is the switching of the CPU from one  process to another.It can Occur only in kernel mode.

A Process is an executing instance of a program.


A context is the contents of a CPU's Register and Program Counter at any point in Time.

A Register is a small amount of very fast memory inside of a CPU that is used to speed the execution  of computer programs by providing quick access.

A Program Counter is a specialized register that indicates the position of the CPU in its instruction sequence and which holds either the address of the instruction being executed or the address of the next instruction to be executed,depending on the specific system.

If we go in detail,The kernel(Core of the operating system)performing the following activities with regard to the process.

1.Suspending the progression of one process and storing the CPU's state(Context)for that process somewhere in memory.

2.Retrieving the context of the next process from memory and restoring it in the CPU's Registers.

3.Returning to the Location indicated by the Program counter(Returning the lines of code at which the process was interrupted)in order to resume the process.

Simply telling A context switch is the kernel suspending execution of one process on the CPU and resuming execution of some other process that had previously been suspended

COMPOSITE DEVICE

USB COMPOSITE DEVICE:

A USB composite device refers to a single gadget that has the  capability of providing multiple functions, for instance a combined keyboard and mouse machine. The devices will typically need a driver for full functionality.

EX:GAME CONTROLLERS.


EXAMPLE DEVICE HAVING MULTIPLE CONFIGURATIONS:

USB camera would have two configurations, one with the Video (camera), Audio (microphone) and Mass Storage features, and

another containing Video (camera), Audio (microphone) and Still Image features. As the configurations are separate the common features between configurations need to be repeated inside each independent configuration descriptor.


ISDN adapter  have two different configurations, one that presents it with a single interface of 128 Kb/s and a second that presents it with two interfaces of 64 Kb/s each.

USER MODE AND KERNEL MODE

USER MODE AND KERNEL MODE:

A processor in a computer running Windows has two different modes: user mode and kernel mode.

The processor switches between the two modes depending on what type of code is running on the processor.

Applications run in user mode, and core operating system components run in kernel mode.

 Many drivers run in kernel mode, but some drivers run in user mode.

Firstly, Intel CPUs have modes of operation called rings which specify the type of instructions and memory available to the running code. There are four rings:

    Ring 0 (also known as kernel mode) has full access to every resource. It is the mode in which the Windows kernel runs.
  
    Rings 1 and 2 can be customized with levels of access but are generally unused unless there are virtual machines running.

    Ring 3 (also known as user mode) has restricted access to resources.

The reason for this is because if all programs ran in kernel mode, they would be able to overwrite each others' memory and possibly bring down the entire system when they crashed.When you start a user-mode application, Windows creates a process for the application.

The process provides the application with a private virtual address space and a private handle table. Because an application's virtual address space is private, one application cannot alter data that belongs to another application.Each application runs in isolation, and if an application crashes, the crash is limited to that one application. Other applications and the operating system are not affected by the crash.

In addition to being private, the virtual address space of a user-mode application is limited. A processor running in user mode cannot access virtual addresses that are reserved for the operating system. Limiting the virtual address space of a user-mode application prevents the application from altering, and possibly damaging, critical operating system data.All code that runs in kernel mode shares a single virtual address space. This means that a kernel-mode driver is not isolated from other drivers and the operating system itself. If a kernel-mode driver accidentally writes to the wrong virtual address,data that belongs to the operating system or another driver could be compromised. If a kernel-mode driver crashes, the entire operating system crashes.



Switching from User Mode to Kernel Mode:

The switch from user mode to kernel mode is not done automatically by CPU. CPU is interrupted by interrupts (timers, keyboard, I/O). When interrupt occurs, CPU stops executing the current running program, switch to kernel mode, executes interrupt handler. This handler saves the state of CPU, performs its operations, restore the state and returns to user mode.

Monday, 26 August 2013

MEMCPY AND MEMMOVE

#include <string.h>
#include <stdio.h>
#include<stdlib.h>
 int main()
 {

  char a[20]="vinayagam";
  char b[20]="vinayagam";
 printf("Address of A:%u",&a);
 printf("Address of B:%u",&b);
  memmove(a+5, a, 20);
   puts(a);
 memcpy(b+5, b, 20);
   puts(b);
   }
The output:

Address of A:2815980

Address of B:2815952.
vinayvinayagam
vinayvinayagam


In this program memmove handles the overlapping of source and destination,But memcpy doesn't

able to handle the overlapping of souce and destination strings.So buffer over run occurs at 'b'.

 

Reason For Not working:


Normally, a memcpy that copies downwards(Downwards means source address will be higher than destination address Ex:memcpy(0x20,0x50,30) will work

perfectly well in practice, because the natural way to do memcpy() by making it just copy things upwards will  just work even for the overlapping case but causes buffer overflow.


To Avoid Overlapping in memcpy:


We can use memcpy in the case of downwards:

Ex:
#include <string.h>
#include <stdio.h>
#include<stdlib.h>
 int main()
 {

  char a[20]="vinayagam";
  char b[20]="vinayagam";
 printf("Address of A:%u",&a);
 printf("Address of B:%u",&b);
  memmove(a+5,a,9);
   puts(a);
 memcpy(b,b+5,4);
   puts(b);
   }

The output:

Address of A:2815980

Address of B:2815952.

vinayvinayagam
agamyagam


 

STRCPY VS MEMCPY

Strcpy:

Strcpy deals with arrays of characters ending in \0.It will fail horribly if there is no '\0'.

On the other hand the syntax of strcpy is:

char *strcpy(char *s1, const char *s2);

s1-destination string.

s2-source string.

It will copy the string pointed by s2 into s1.

While copying is there any overlapping occures means its performance is undefined.

The disadvantage of strcpy is, It doesn't perform Bounds Checking(Setting or Verifying the size of data before storing the data into the Buffers).

For Example:

#include <stdio.h>
#include <string.h>
int main()
 {
    char buf[4]= "";
    char sun[12]= "how are you";
    strcpy(buf, sun);  
    printf("%s\n", buf);
    return 0;

 }

In the above program The size of the source is high compared to size of the destination.

So While debugging Buffer overflow occurs.

We choose alternative Function like memcpy which perform Bound checking.We can consider strncpy() also.


Memcpy:

The Syntax of Memcpy is

void *memcpy(void*dest,const void* src,int n)

dest-destination buffer.

src-source buffer.

In that n defines the number of bytes to be transferred.
Example:

#include <stdio.h>
#include <string.h>
int main()
 {
    char buf[4]= "";
    char sun[12]= "how are you";
    memcpy(buf, sun, 4);  
    printf("%s\n", buf);
    return 0;

 }

In the above program only 4 bytes of data can be transfered to buf from sun.

So with the help of this memcpy we can avoid buffer overflow.

But the disadvantage of memcpy is when overlapping between source and destination occurs

means it also made buffer overflow while debugging.It does n't copy the data safely before overlapping.

That problem can be solved with the help of memmove function.

 

The other difference between strcpy and memcpy is explained below the program:

#include <stdio.h>
#include <string.h>

int main()
{
  char s1[10] = "abc\0def";
  char s2[10] = "";
  char m1[10] = "abc\0def";
  char m2[10] = "";
  int i;

  strcpy(s2,s1);
  for(i=0;i<10;i++)
  {
  printf("STRCPY %d= %c\n",i,s2[i]);
}

  memcpy(m2,m1,10);
  for(i = 0; i <10; i++)
    {
      printf("MEMCPY %d - %c\n", i, m2[i]);
    }

  return 0;
}
The Output of the above program is:

STRCPY 0= a
STRCPY 1= b
STRCPY 2= c
STRCPY 3=
STRCPY 4=
STRCPY 5=
STRCPY 6=
STRCPY 7=
STRCPY 8=
STRCPY 9=
MEMCPY 0 - a
MEMCPY 1 - b
MEMCPY 2 - c
MEMCPY 3 -
MEMCPY 4 - d
MEMCPY 5 - e
MEMCPY 6 - f
MEMCPY 7 -
MEMCPY 8 -
MEMCPY 9 -

So in the above result the function strcpy copy the contents until it finds '\0'(NULL)character.

But memcpy copies the content without considering the NULL termination.

 

Strcpy with integers:


#include<stdio.h>
#include<string.h>
int main()
 {
 int dst[3]={60,90,50};
 int src[3]={30,25,35};
 strcpy((char *)dst,(char *)src);
 for(int i=0;i<3;i++0
  {
  printf("dst=%d\n", dst[i]);
  }

 }

The output is:

dst=30
dst=90
dst=50


Even we use type casting for integers it won't workout in strcpy.Because size of the integers and charcters are different.

 

So The other thing which makes variation between strcpy()and memcpy() is, memcpy() is adaptable for both characters and strings.

strcpy() is adaptable only for strings.

 

 

 

 


 

STRUCTURE PADDING

Structure alignment:

 The Structure alignment for 32 bit machine will be in either increasing/decreasing order.

 

Ex:

Typical Structure alignment

Struct tag

{

char  c;       //1byte

short int d;   //2bytes

int   e;       //4bytes

double f;      //8bytes

};

Structure Padding:

 In order to align the data in memory,  one or more empty bytes(addresses) are inserted (or left empty) between memory addresses

which are allocated for other structure members while memory allocation. This concept is called structure padding.

Why Structure Padding?

 Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit processor) from memory at a time.

To make use of this advantage of processor, data are always aligned as 4 bytes package which leads to insert empty addresses between other member’s address.

 

Because of this structure padding concept in C, size of the structure is always not same as what we think.

 

Ex:

struct structure1

 {

       short int id;

       char name[20];

       char c;

       long percentage;

       double marks;

 };

 

We thing that the size of structure becomes (short int)2 bytes+(char name[20])20 bytes+(char c)1 byte+(long percentage)4 bytes+(double marks)8 bytes=35 bytes.

 

But the actual size of the structure given by compiler is 40  bytes Because of structure padding.

Padding done as follows:

2 Bytes+2 Bytes(padding)+20 bytes+1 byte+3 bytes(padding)+4 bytes+8 bytes=40 Bytes.

If we change the alignment of Structure Like below means:

struct structure2

 {

 char c;

 long percentage;

 short int id;

 double marks;

 char name[20];

 };

Then the size of the structure becomes

1byte+3bytes(padding)+4bytes+2bytes+6bytes(padding)+8bytes+20bytes=44 bytes.

So If we align the structure in an order means

struct structure1

 {

       char c;

       short int id;

       long percentage;

       double marks;

       char name[20];

 };

Then the size of the structure becomes

1 byte+2bytes+1byte(padding)+4bytes+8bytes+20bytes=36bytes.

 

So if we aligned a structure in an order(in this example increasing)means we got the size of the structure minimum.

How to avoid Structure padding?

1.By proper aligning of structures we can avoid structure padding.

2.we can also use #pragma pack(1)Function to reduce the structure padding.

 

#pragma pack(n):

The purpose of #pragma pack is to Sets the alignment of all aggregate members to a specified byte boundary.

Here n is the alignment in bytes, valid alignment values being 1, 2, 4 and 8.

So if we use #pragma pack(1) means we can get the size of the structure as 35 bytes as what we have calculate.

But, If we use #pragma pack() The speed of the processor becomes slow.Because the processor align the members by padding bytes(According to word length of processor) to get high speed.

If we use pragma means at compiler or processor point of view the members are misaligned. So for accessing those members

we require more coding's which leads to PERFORMANCE PENALTY.

 

Then NEED OF #pragma pack:

We use pragma pack only when our structure match an exact data layout. Ex: Networking protocols and device drivers accessing HW registers.

Linked list Vs Array

Linked list and array:
Linked list and array are same to store the collection of data.
But the difference is array only store the same type of Data. Linked List store the different kinds of data using structures.
Structures are used to create a collection of data with different types.


The Disadvantage of using array is we can initially declare the array[100].
It means at compile time it will be allocated for 100 blocks.
But most of the time we use only 20 to 30 blocks of array.
So that the remaining memory spaces are wasted.
For recovering this we need to initialize the array dynamically at runtime.
That is done with the help of malloc() function and Pointers

Sunday, 28 July 2013

C IMPORTANT QUESTIONS

1. What does static variable mean?
 Static variables are the variables which retain their values between the function calls. They are initialized only once their scope is within the function in which they are defined.


2. What is a pointer?
Pointers are variables which stores the address of another variable. That variable may be a scalar (including another pointer), or an aggregate (array or structure). The pointed-to object may be part of a larger object, such as a field of a structure or an element in an array.


3. What are the uses of a pointer?
 Pointer is used in the following cases
i) It is used to access array elements
ii) It is used for dynamic memory allocation.
iii) It is used in Call by reference
iv) It is used in data structures like trees, graph, linked list etc.


4. What is a structure?
 Structure constitutes a super data type which represents several different data types in a single unit. A structure can be initialized if it is static or global.


5. What is a union?
Union is a collection of heterogeneous data type but it uses efficient memory utilization technique by allocating enough memory to hold the largest member. Here a single area of memory contains values of different types at different time. A union can never be initialized.


6. What are the differences between structures and union?
 A structure variable contains each of the named members, and its size is large enough to hold all the members. Structure elements are of same size.
A union contains one of the named members at a given time and is large enough to hold the largest member. Union element can be of different sizes.


7. What are the differences between structures and arrays?
 Structure is a collection of heterogeneous data type but array is a collection of homogeneous data types.
Array
1-It is a collection of data items of same data type.
2-It has declaration only
3-.There is no keyword.
4- array name represent the address of the starting element.
Structure
1-It is a collection of data items of different data type.
2- It has declaration and definition
3- keyword struct is used
4-Structure name is known as tag it is the short hand notation of the declaration.


8. In header files whether functions are declared or defined?
 Functions are declared within header file. That is function prototypes exist in a header file,not function bodies. They are defined in library (lib).



9. What are the differences between malloc () and calloc ()?
Malloc Calloc 1-Malloc takes one argument Malloc(a);where a number of bytes 2-memory allocated contains garbage values
1-Calloc takes two arguments Calloc(b,c) where b no of object and c size of object
2-It initializes the contains of block of memory to zerosMalloc takes one argument, memory allocated contains garbage values.
It allocates contiguous memory locations. Calloc takes two arguments, memory allocated contains all zeros, and the memory allocated is not contiguous.



10. What are macros? What are its advantages and disadvantages?
Ans: Macros are abbreviations for lengthy and frequently used statements. When a macro is called the entire code is substituted by a single line though the macro definition is of several lines.
The advantage of macro is that it reduces the time taken for control transfer as in case of
function.
The disadvantage of it is here the entire code is substituted so the program becomes
lengthy if a macro is called several times.



11. Difference between pass by reference and pass by value?
Ans: Pass by reference passes a pointer to the value. This allows the callee to modify the variable directly.Pass by value gives a copy of the value to the callee. This allows the callee to modify the value without modifying the variable. (In other words, the callee simply cannot modify the variable, since it lacks a reference to it.)


12. What is static identifier?
Ans: A file-scope variable that is declared static is visible only to functions within that file. A
function-scope or block-scope variable that is declared as static is visible only within that scope. Furthermore, static variables only have a single instance. In the case of function- or block-scope variables, this means that the variable is not “automatic” and thus retains its value across function invocations.


13. Where is the auto variables stored?
Ans: Auto variables can be stored anywhere, so long as recursion works. Practically, they’re stored on
the stack. It is not necessary that always a stack exist. You could theoretically allocate function invocation records from the heap.


14. Where does global, static, and local, register variables, free memory and C Program instructions get stored?
Ans: Global: Wherever the linker puts them. Typically the “BSS segment” on many platforms.
Static: Again, wherever the linker puts them. Often, they’re intermixed with the globals. The only difference between globals and statics is whether the linker will resolve the symbols across compilation units.Local: Typically on the stack, unless the variable gets register allocated and never spills.Register: Nowadays, these are equivalent to “Local” variables. They live on the stack unless they get register-allocated.



15. Difference between arrays and linked list?
Ans: An array is a repeated pattern of variables in contiguous storage. A linked list is a set of
structures scattered through memory, held together by pointers in each element that point to the next element. With an array, we can (on most architectures) move from one element to the next by adding a fixed constant to the integer value of the pointer. With a linked list, there is a “next” pointer in each structure which says what element comes next.


16. What are enumerations?
Ans: They are a list of named integer-valued constants. Example:enum color { black , orange=4,
yellow, green, blue, violet };This declaration defines the symbols “black”, “orange”, “yellow”, etc. to have the values “1,” “4,” “5,” … etc. The difference between an enumeration and a macro is that the enum actually declares a type, and therefore can be type checked.


17. Describe about storage allocation and scope of global, extern, static, local and register variables?
Ans:
Globals have application-scope. They’re available in any compilation unit that includes an
appropriate declaration (usually brought from a header file). They’re stored wherever the linker puts them, usually a place called the “BSS segment.”
Extern? This is essentially “global.”
Static: Stored the same place as globals, typically, but only available to the compilation unit that contains them. If they are block-scope global, only available within that block and its subblocks.
Local: Stored on the stack, typically. Only available in that block and its subblocks.
(Although pointers to locals can be passed to functions invoked from within a scope where that local is valid.)
Register: See tirade above on “local” vs. “register.” The only difference is that
the C compiler will not let you take the address of something you’ve declared as “register.”



18. What are register variables? What are the advantages of using register variables?
Ans: If a variable is declared with a register storage class,it is known as register variable.The
register variable is stored in the cpu register instead of main memory.Frequently used variables
are declared as register variable as it’s access time is faster.



19. What is the use of typedef?
Ans: The typedef help in easier modification when the programs are ported to another machine.
A descriptive new name given to the existing data type may be easier to understand the code.




20. Can we specify variable field width in a scanf() format string? If possible how?
Ans: All field widths are variable with scanf(). You can specify a maximum field width for a given
field by placing an integer value between the ‘%’ and the field type specifier. (e.g. %64s). Such a specifier will still accept a narrower field width.
The one exception is %#c (where # is an integer). This reads EXACTLY # characters, and it is the
only way to specify a fixed field width with scanf().

 


21. Out of fgets() and gets() which function is safe to use and why?
Ans: fgets() is safer than gets(), because we can specify a maximum input length. Neither one is completely safe, because the compiler can’t prove that programmer won’t overflow the buffer he pass to fgets ().


22. Difference between strdup and strcpy?
Ans: Both copy a string. strcpy wants a buffer to copy into. strdup allocates a buffer using malloc().
Unlike strcpy(), strdup() is not specified by ANSI .



23. What is recursion?
Ans: A recursion function is one which calls itself either directly or indirectly it must halt at a definite point to avoid infinite recursion.



24. Differentiate between for loop and a while loop? What are it uses?
Ans: For executing a set of statements fixed number of times we use for loop while when the number of
iterations to be performed is not known in advance we use while loop.



25. What is storage class? What are the different storage classes in C?
Ans: Storage class is an attribute that changes the behavior of a variable. It controls the lifetime, scope and linkage. The storage classes in c are auto, register, and extern, static, typedef.



26. What the advantages of using Unions?
Ans: When the C compiler is allocating memory for unions it will always reserve enough room for the
largest member.



27. What is the difference between Strings and Arrays?
Ans: String is a sequence of characters ending with NULL .it can be treated as a one dimensional array
of characters terminated by a NULL character.



28. What is a far pointer? Where we use it?
Ans: In large data model (compact, large, huge) the address B0008000 is acceptable because in these
model all pointers to data are 32bits long. If we use small data model(tiny, small, medium) the above address won’t work since in these model each pointer is 16bits long. If we are working in a small data model and want to access the address B0008000 then we use far pointer. Far pointer is always treated as a 32bit pointer and contains a segment address and offset address both of 16bits each. Thus the address is represented using segment : offset format B000h:8000h. For any
given memory address there are many possible far address segment : offset pair. The segment register contains the address where the segment begins and offset register contains the offset of data/code from where segment begins.



29. What is a huge pointer?
Ans: Huge pointer is 32bit long containing segment address and offset address. Huge pointers are
normalized pointers so for any given memory address there is only one possible huge address segment: offset pair. Huge pointer arithmetic is doe with calls to special subroutines so its arithmetic slower than any other pointers.



30. What is a normalized pointer, how do we normalize a pointer?
Ans: It is a 32bit pointer, which has as much of its value in the segment register as possible. Since
a segment can start every 16bytes so the offset will have a value from 0 to F. for normalization convert the address into 20bit address then use the 16bit for segment address and 4bit for the offset address. Given a pointer 500D: 9407,we convert it to a 20bitabsolute address 549D7,Which then normalized to 549D:0007.



31. What is near pointer?
Ans: A near pointer is 16 bits long. It uses the current content of the CS (code segment) register (if
the pointer is pointing to code) or current contents of DS (data segment) register (if the pointer is pointing to data) for the segment part, the offset part is stored in a 16 bit near pointer. Using near pointer limits the data/code to 64kb segment.



32. In C, why is the void pointer useful? When would you use it?
Ans: The void pointer is useful because it is a generic pointer that any pointer can be cast into and
back again without loss of information.



33. What is a NULL Pointer? Whether it is same as an uninitialized pointer?
Ans: Null pointer is a pointer which points to nothing but uninitialized pointer may point to anywhere.



34. Are pointers integer?
Ans: No, pointers are not integers. A pointer is an address. It is a positive number.



35. What does the error ‘Null Pointer Assignment’ means and what causes this error?
Ans: As null pointer points to nothing so accessing a uninitialized pointer or invalid location may cause an error.



36. What is generic pointer in C?
Ans: In C void* acts as a generic pointer. When other pointer types are assigned to generic pointer,
conversions are applied automatically (implicit conversion).



37. Are the expressions arr and &arr same for an array of integers?
Ans: Yes for array of integers they are same.



38. IMP>How pointer variables are initialized?
Ans: Pointer variables are initialized by one of the following ways.
I. Static memory allocation
II. Dynamic memory allocation



39. What is static memory allocation?
Ans: Compiler allocates memory space for a declared variable. By using the address of operator, the
reserved address is obtained and this address is assigned to a pointer variable. This way of assigning pointer value to a pointer variable at compilation time is known as static memory allocation.



40. What is dynamic memory allocation?
Ans: A dynamic memory allocation uses functions such as malloc() or calloc() to get memory dynamically. If these functions are used to get memory dynamically and the values returned by these function are assigned to pointer variables, such a way of allocating memory at run time is known as dynamic memory allocation.



41. What is the purpose of realloc?
Ans: It increases or decreases the size of dynamically allocated array. The function realloc (ptr,n) uses two arguments. The first argument ptr is a pointer to a block of memory for which the size is to be altered. The second argument specifies the new size. The size may be increased or decreased. If sufficient space is not available to the old region the function may create a new region.



42. What is pointer to a pointer?
Ans: If a pointer variable points another pointer value. Such a situation is known as a pointer to a pointer.
Example:
int *p1,**p2,v=10;
P1=&v; p2=&p1;
Here p2 is a pointer to a pointer.



43. What is an array of pointers?
Ans: if the elements of an array are addresses, such an array is called an array of pointers.



44. Difference between linker and linkage?
Ans: Linker converts an object code into an executable code by linking together the necessary built in
functions. The form and place of declaration where the variable is declared in a program determine the linkage of variable.



45. Is it possible to have negative index in an array?
Ans: Yes it is possible to index with negative value provided there are data stored in this location. Even if it is illegal to refer to the elements that are out of array bounds, the compiler will not produce error because C has no check on the bounds of an array.



46. Why is it necessary to give the size of an array in an array declaration?
Ans: When an array is declared, the compiler allocates a base address and reserves enough space in
memory for all the elements of the array. The size is required to allocate the required space and hence size must be mentioned.



47. What modular programming?
Ans: If a program is large, it is subdivided into a number of smaller programs that are called modules or subprograms. If a complex problem is solved using more modules, this approach is known as modular programming.



48. What is a function?
Ans: A large program is subdivided into a number of smaller programs or subprograms. Each subprogram
specifies one or more actions to be performed for the larger program. Such sub programs are called functions.



49. What is an argument?
Ans: An argument is an entity used to pass data from the calling to a called function.



50. What are built in functions?
Ans: The functions that are predefined and supplied along with the compiler are known as built-in functions. They are also known as library functions.



51. Difference between formal argument and actual argument?
Ans: Formal arguments are the arguments available in the function definition. They are preceded by
their own data type. Actual arguments are available in the function call. These arguments are given
as constants or variables or expressions to pass the values to the function.


52. Is it possible to have more than one main() function in a C program ?
Ans: The function main() can appear only once. The program execution starts from main.



53. What is the difference between an enumeration and a set of pre-processor # defines?
Ans: There is hardly any difference between the two, except that #defines has a global effect (throughout the file) whereas an enumeration can have an effect local to the block if desired. Some advantages of enumeration are that the numeric values are automatically assigned whereas in #define we have to explicitly define them. A disadvantage is that we have no control over the size of enumeration variables.



54. How are Structure passing and returning implemented by the complier?
Ans: When structures are passed as argument to functions, the entire structure is typically pushed on
the stack. To avoid this overhead many programmer often prefer to pass pointers to structure instead of actual structures. Structures are often returned from functions in a location pointed to by an extra, compiler-supported ‘hidden’ argument to the function.



55. IMP>what is the similarity between a Structure, Union and enumeration?
Ans: All of them let the programmer to define new data type.



56. Can a Structure contain a Pointer to itself?
Ans: Yes such structures are called self-referential structures.



57. How can we read/write Structures from/to data files?
Ans: To write out a structure we can use fwrite() as Fwrite( &e, sizeof(e),1,fp);Where e is a structure
variable. A corresponding fread() invocation can read the structure back from file. calling fwrite() it writes out sizeof(e) bytes from the address &e. Data files written as memory images with fwrite(),however ,will not be portable, particularly if they contain floating point fields or Pointers. This is because memory layout of structures is machine and compiler
dependent. Therefore, structures written as memory images cannot necessarily be read back by programs running on other machine, and this is the important concern if the data files you’re writing will ever be interchanged between machines.



58. Write a program which employs Recursion?
Ans: int fact(int n) { return n > 1 ? n * fact(n – 1) : 1; }



59.Write a program which uses Command Line Arguments?

Ans:

#include
void main(int argc,char *argv[])
{
int i;
clrscr();
for(i=0;i
printf(“\n%d”,argv[i]);
}



60. Difference between array and pointer?
Ans:
Array
1- Array allocates space automatically
2- It cannot be resized
3- It cannot be reassigned
4- sizeof (arrayname) gives the number of bytes occupied by the array.
Pointer
1-Explicitly assigned to point to an allocated space.
2-It can be sized using realloc()
3-pointer can be reassigned.
4-sizeof (p) returns the number of bytes used to store the pointer variable p.




61. What do the ‘c’ and ‘v’ in argc and argv stand for?
Ans: The c in argc(argument count) stands for the number of command line argument the program is
invoked with and v in argv(argument vector) is a pointer to an array of character string that contain the arguments.



62. IMP>what are C tokens?
Ans: There are six classes of tokens: identifier, keywords, constants, string literals, operators and other separators.



63. What are C identifiers?
Ans: These are names given to various programming element such as variables, function, arrays.It is a combination of letter, digit and underscore.It should begin with letter. Backspace is not allowed.



64. Difference between syntax vs logical error?
Ans:
Syntax Error
1-These involves validation of syntax of language.
2-compiler prints diagnostic message.

Logical Error
1-logical error are caused by an incorrect algorithm or by a statement mistyped in such a way
that it doesn’t violet syntax of language.
2-difficult to find.



65. What is preincrement and post increment?
Ans: ++n (pre increment) increments n before its value is used in an assignment operation or any
expression containing it. n++ (post increment) does increment after the value of n is used.



66. Write a program to interchange 2 variables without using the third one.
Ans:
a ^= b; ie a=a^b
b ^= a; ie b=b^a;
a ^= b ie a=a^b;
here the numbers are converted into binary and then xor operation is performed.
You know, you’re just asking “have you seen this overly clever trick that’s not worth applying on
modern architectures and only really applies to integer variables?”



67. What is the maximum combined length of command line arguments including the space between adjacent arguments?
Ans: It depends on the operating system.



68. What are bit fields? What is the use of bit fields in a Structure declaration?
Ans: A bit field is a set of adjacent bits within a single implementation based storage unit that we
will call a “word”.
The syntax of field definition and access is based on structure.
Struct {
unsigned int k :1;
unsigned int l :1;
unsigned int m :1;
}flags;
the number following the colon represents the field width in bits.Flag is a variable that contains three bit fields.



69. What is a preprocessor, what are the advantages of preprocessor?
Ans: A preprocessor processes the source code program before it passes through the compiler.
1- a preprocessor involves the readability of program
2- It facilitates easier modification
3- It helps in writing portable programs
4- It enables easier debugging
5- It enables testing a part of program
6- It helps in developing generalized program



70. What are the facilities provided by preprocessor?
Ans:
1-file inclusion
2-substitution facility
3-conditional compilation




71. What are the two forms of #include directive?
Ans:
1.#include”filename”
2.#include
the first form is used to search the directory that contains the source file.If the search fails in the home directory it searches the implementation defined locations.In the second form ,the preprocessor searches the file only in the implementation defined locations.



72. How would you use the functions randomize() and random()?
Ans:
Randomize() initiates random number generation with a random value.
Random() generates random number between 0 and n-1;



73. What do the functions atoi(), itoa() and gcvt() do?
Ans:
atoi() is a macro that converts integer to character.
itoa() It converts an integer to string
gcvt() It converts a floating point number to string



74. How would you use the functions fseek(), freed(), fwrite() and ftell()?
Ans:
fseek(f,1,i) Move the pointer for file f a distance 1 byte from location i.
fread(s,i1,i2,f) Enter i2 dataitems,each of size i1 bytes,from file f to string s.
fwrite(s,i1,i2,f) send i2 data items,each of size i1 bytes from string s to file f.
ftell(f) Return the current pointer position within file f.

The data type returned for functions fread,fseek and fwrite is int and ftell is long int.



75. What is the difference between the functions memmove() and memcpy()?
Ans: The arguments of memmove() can overlap in memory. The arguments of memcpy() cannot.



76. What is a file?
Ans: A file is a region of storage in hard disks or in auxiliary storage devices.It contains bytes of
information .It is not a data type.



77. IMP>what are the types of file?
Ans: Files are of two types
1-high level files (stream oriented files) :These files are accessed using library functions
2-low level files(system oriented files) :These files are accessed using system calls



78. IMP>what is a stream?
Ans: A stream is a source of data or destination of data that may be associated with a disk or other
I/O device. The source stream provides data to a program and it is known as input stream. The destination stream eceives the output from the program and is known as output stream.



79. What is meant by file opening?
Ans: The action of connecting a program to a file is called opening of a file. This requires creating
an I/O stream before reading or writing the data.



80. What is FILE?
Ans: FILE is a predefined data type. It is defined in stdio.h file.



81. What is a file pointer?
Ans: The pointer to a FILE data type is called as a stream pointer or a file pointer. A file pointer points to the block of information of the stream that had just been opened.



82. How is fopen()used ?
Ans: The function fopen() returns a file pointer. Hence a file pointer is declared and it is assigned
as
FILE *fp;
fp= fopen(filename,mode);
filename is a string representing the name of the file and the mode represents:
“r” for read operation
“w” for write operation
“a” for append operation
“r+”,”w+”,”a+” for update operation



83.How is a file closed ?
Ans: A file is closed using fclose() function
Eg. fclose(fp);
Where fp is a file pointer.



84. What is a random access file?
Ans:
A file can be accessed at random using fseek() function
fseek(fp,position,origin);
fp file pointer
position number of bytes offset from origin
origin 0,1 or 2 denote the beginning ,current position or end of file respectively.



85. What is the purpose of ftell ?
Ans: The function ftell() is used to get the current file represented by the file pointer.
ftell(fp);
returns a long integer value representing the current file position of the file pointed by the
file pointer fp.If an error occurs ,-1 is returned.



86. What is the purpose of rewind() ?
Ans: The function rewind is used to bring the file pointer to the beginning of the file.
Rewind(fp);
Where fp is a file pointer.Also we can get the same effect by
feek(fp,0,0);



87. Difference between a array name and a pointer variable?
Ans: A pointer variable is a variable where as an array name is a fixed address and is not a
variable. A
pointer variable must be initialized but an array name cannot be initialized. An array name being a constant value , ++ and — operators cannot be applied to it.



88. Represent a two-dimensional array using pointer?
Ans:
Address of a[I][j] Value of a[I][j]
&a[I][j]
or
a[I] + j
or
*(a+I) + j
*&a[I][j] or a[I][j]
or
*(a[I] + j )
or
*( * ( a+I) +j )



89. Difference between an array of pointers and a pointer to an array?
Ans:
Array of pointers
1- Declaration is: data_type *array_name[size];
2-Size represents the row size.
3- The space for columns may be dynamically

Pointers to an array
1-Declaration is data_type ( *array_name)[size];
2-Size represents the column size.



90. Can we use any name in place of argv and argc as command line arguments ?
Ans: yes we can use any user defined name in place of argc and argv;

Related Fresher Interview Questions


a constant pointer and pointer to a constant?
Ans:
const char *p; //pointer to a const character.
char const *p; //pointer to a const character.
char * const p; //const pointer to a char variable.
const char * const p; // const pointer to a const character.



93. Is the allocated space within a function automatically deallocated when the function returns?
Ans: No pointer is different from what it points to .Local variables including local pointers
variables in a function are deallocated automatically when function returns.,But in case of a
local pointer variable ,deallocation means that the pointer is deallocated and not the block of
memory allocated to it. Memory dynamically allocated always persists until the allocation is freed
or the program terminates.



94. Discuss on pointer arithmetic?
Ans:
1- Assignment of pointers to the same type of pointers.
2- Adding or subtracting a pointer and an integer.
3-subtracting or comparing two pointer.
4-incrementing or decrementing the pointers pointing to the elements of an array. When a pointer
to an integer is incremented by one , the address is incremented by two. It is done automatically
by the compiler.
5-Assigning the value 0 to the pointer variable and comparing 0 with the pointer. The pointer
having address 0 points to nowhere at all.



95. What is the invalid pointer arithmetic?
Ans:
i) adding ,multiplying and dividing two pointers.
ii) Shifting or masking pointer.
iii) Addition of float or double to pointer.
iv) Assignment of a pointer of one type to a pointer of another type 



96. What are the advantages of using array of pointers to string instead of an array of strings?
Ans:
i) Efficient use of memory.
ii) Easier to exchange the strings by moving their pointers while sorting.



97. Are the expressions *ptr ++ and ++ *ptr same?
Ans: No,*ptr ++ increments pointer and not the value pointed by it. Whereas ++ *ptr
increments the value being pointed to by ptr.



98. What would be the equivalent pointer expression foe referring the same element as
a[p][q][r][s] ?
Ans : *( * ( * ( * (a+p) + q ) + r ) + s)



99. Are the variables argc and argv are always local to main?

Ans: Yes they are local to main.



100. Can main () be called recursively?
Ans: Yes any function including main () can be called recursively.



101. IMP>Can we initialize unions?
Ans: ANSI Standard C allows an initializer for the first member of a union. There is no standard way
of initializing any other member (nor, under a pre-ANSI compiler, is there generally any way of
initializing a union at all).



102. What’s the difference between these two declarations?
Ans: struct x1 { … };
typedef struct { … } x2;
The first form declares a structure tag; the second declares a typedef. The main difference is that the second declaration is of a slightly more abstract type.its users don’t necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it.



103. Why doesn’t this code: a[i] = i++; work?
Ans: The subexpression i++ causes a side effect.it modifies i’s value.which leads to undefined
behavior since i is also referenced elsewhere in the same expression.



104.WHy doesn’t struct x { … };
x thestruct;
work?
Ans:
C is not C++. Typedef names are not automatically generated for structure tags.



105. Why can’t we compare structures?
Ans:
There is no single, good way for a compiler to implement structure comparison which is consistent with C’s low-level flavor. A simple byte-by-byte comparison could founder on random bits present in unused “holes” in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison might require unacceptable amounts of repetitive code for large structures.



106. How are structure passing and returning implemented?
Ans: When structures are passed as arguments to functions, the entire structure is typically pushed on
the stack, using as many words as are required. Some compilers merely pass a pointer to the structure, though they may have to make a local copy to preserve pass-by-value semantics.
Structures are often returned from functions in a location pointed to by an extra,compiler-supplied “hidden” argument to the function. Some older compilers used a special,static location for structure returns, although this made structure-valued functions non-reentrant, which ANSI C disallows.