Monday, 22 August 2011

Operating System


What is a Real-Time System?

- A real time process is a process that must respond to the events within a certain time period. A real time operating system is an operating system that can run real time processes successfully

What is a Safe State and what is its use in deadlock avoidance?

- When a process requests an available resource, system must decide if immediate allocation leaves the system in a safe state. System is in safe state if there exists a safe sequence of all processes. Deadlock Avoidance: ensure that a system will never enter an unsafe state.

What is cache memory?

- Cache memory is random access memory (RAM) that a computer microprocessor can access more quickly than it can access regular RAM. As the microprocessor processes data, it looks first in the cache memory and if it finds the data there (from a previous reading of data), it does not have to do the more time-consuming reading of data from larger memory.

What is Context Switch?

- Switching the CPU to another process requires saving the state of the old process and loading the saved state for the new process. This task is known as a context switch. Context-switch time is pure overhead, because the system does no useful work while switching. Its speed varies from machine to machine, depending on the memory speed, the number of registers which must be copied, the existed of special instructions(such as a single instruction to load or store all registers).

What is CPU Scheduler?

- Selects from among the processes in memory that are ready to execute, and allocates the CPU to one of them. CPU scheduling decisions may take place when a process: 1.Switches from running to waiting state. 2.Switches from running to ready state. 3.Switches from waiting to ready. 4.Terminates. Scheduling under 1 and 4 is non-preemptive. All other scheduling is preemptive.

What is Dispatcher?

- Dispatcher module gives control of the CPU to the process selected by the short-term scheduler; this involves: Switching context, Switching to user mode, Jumping to the proper location in the user program to restart that program, dispatch latency – time it takes for the dispatcher to stop one process and start another running.

What is DRAM? In which form does it store data?

- DRAM is not the best, but it’s cheap, does the job, and is available almost everywhere you look. DRAM data resides in a cell made of a capacitor and a transistor. The capacitor tends to lose data unless it’s recharged every couple of milliseconds, and this recharging tends to slow down the performance of DRAM compared to speedier RAM types.

What is fragmentation? Different types of fragmentation?

- Fragmentation occurs in a dynamic memory allocation system when many of the free blocks are too small to satisfy any request. External Fragmentation: External Fragmentation happens when a dynamic memory allocation algorithm allocates some memory and a small piece is left over that cannot be effectively used. If too much external fragmentation occurs, the amount of usable memory is drastically reduced. Total memory space exists to satisfy a request, but it is not contiguous. Internal Fragmentation: Internal fragmentation is the space wasted inside of allocated memory blocks because of restriction on the allowed sizes of allocated blocks. Allocated memory may be slightly larger than requested memory; this size difference is memory internal to a partition, but not being used

What is hard disk and what is its purpose?

Hard disk is the secondary storage device, which holds the data in bulk, and it holds the data on the magnetic medium of the disk. Hard disks have a hard platter that holds the magnetic medium, the magnetic medium can be easily erased and rewritten, and a typical desktop machine will have a hard disk with a capacity of between 10 and 40 gigabytes. Data is stored onto the disk in the form of files.

What is multi tasking, multi programming, multi threading?

Multi programming: Multiprogramming is the technique of running several programs at a time using timesharing. It allows a computer to do several things at the same time. Multiprogramming creates logical parallelism. The concept of multiprogramming is that the operating system keeps several jobs in memory simultaneously. The operating system selects a job from the job pool and starts executing a job, when that job needs to wait for any i/o operations the CPU is switched to another job. So the main idea here is that the CPU is never idle. Multi tasking: Multitasking is the logical extension of multiprogramming .The concept of multitasking is quite similar to multiprogramming but difference is that the switching between jobs occurs so frequently that the users can interact with each program while it is running. This concept is also known as time-sharing systems. A time-shared operating system uses CPU scheduling and multiprogramming to provide each user with a small portion of time-shared system. Multi threading: An application typically is implemented as a separate process with several threads of control. In some situations a single application may be required to perform several similar tasks for example a web server accepts client requests for web pages, images, sound, and so forth. A busy web server may have several of clients concurrently accessing it. If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time. The amount of time that a client might have to wait for its request to be serviced could be enormous. So it is efficient to have one process that contains multiple threads to serve the same purpose. This approach would multithread the web-server process, the server would create a separate thread that would listen for client requests when a request was made rather than creating another process it would create another thread to service the request. To get the advantages like responsiveness, Resource sharing economy and utilization of multiprocessor architectures multithreading concept can be used.

What is the cause of thrashing? How does the system detect thrashing?

Once it detects thrashing, what can the system do to eliminate this problem? – Thrashing is caused by under allocation of the minimum number of pages required by a process, forcing it to continuously page fault. The system can detect thrashing by evaluating the level of CPU utilization as compared to the level of multiprogramming. It can be eliminated by reducing the level of multiprogramming.

What is the difference between Hard and Soft real-time systems?

- A hard real-time system guarantees that critical tasks complete on time. This goal requires that all delays in the system be bounded from the retrieval of the stored data to the time that it takes the operating system to finish any request made of it. A soft real time system where a critical real-time task gets priority over other tasks and retains that priority until it completes. As in hard real time systems kernel delays need to be bounded

What is the important aspect of a real-time system or Mission Critical Systems?

A real time operating system has well defined fixed time constraints. Process must be done within the defined constraints or the system will fail. An example is the operating system for a flight control computer or an advanced jet airplane. Often used as a control device in a dedicated application such as controlling scientific experiments, medical imaging systems, industrial control systems, and some display systems. Real-Time systems may be either hard or soft real-time. Hard real-time: Secondary storage limited or absent, data stored in short term memory, or read-only memory (ROM), Conflicts with time-sharing systems, not supported by general-purpose operating systems. Soft real-time: Limited utility in industrial control of robotics, Useful in applications (multimedia, virtual reality) requiring advanced operating-system features.

What is the state of the processor, when a process is waiting for some event to occur?

Waiting state

What is Throughput, Turnaround time, waiting time and Response time?

Throughput – number of processes that complete their execution per time unit. Turnaround time – amount of time to execute a particular process. Waiting time – amount of time a process has been waiting in the ready queue. Response time – amount of time it takes from when a request was submitted until the first response is produced, not output (for time-sharing environment).

What is virtual memory?

Virtual memory is hardware technique where the system appears to have more memory that it actually does. This is done by time-sharing, the physical memory and storage parts of the memory one disk when they are not actively being used.

What resources are used when a thread created? How do they differ from those when a process is created?

When a thread is created the threads does not require any new resources to execute the thread shares the resources like memory of the process to which they belong to. The benefit of code sharing is that it allows an application to have several different threads of activity all within the same address space. Whereas if a new process creation is very heavyweight because it always requires new address space to be created and even if they share the memory then the inter process communication is expensive when compared to the communication between the threads.

While running DOS on a PC, which command would be used to duplicate the entire diskette?

diskcopy

Why paging is used?

-Paging is solution to external fragmentation problem which is to permit the logical address space of a process to be noncontiguous, thus allowing a process to be allocating physical memory wherever the latter is available.

What are the basic functions of an operating system?

- Operating system controls and coordinates the use of the hardware among the various applications programs for various uses. Operating system acts as resource allocator and manager. Since there are many possibly conflicting requests for resources the operating system must decide which requests are allocated resources to operating the computer system efficiently and fairly. Also operating system is control program which controls the user programs to prevent errors and improper use of the computer. It is especially concerned with the operation and control of I/O devices.

OPERATING SYSTEM TYPES

As computers have progressed and developed so have the types of operating systems. Below is a basic list of the different types of operating systems and a few examples of Operating Systems that fall into each of the categories. Many computer Operating Systems will fall into more than one of the below categories.
GUI – Short for Graphical User Interface, a GUI Operating System contains graphics and icons and is commonly navigated by using a computer mouse. See our GUI dictionary definition for a complete definition. Below are some examples of GUI Operating Systems.
System 7.x
Windows 98
Windows CE

Multi-user – A multi-user Operating System allows for multiple users to use the same computer at the same time and/or different times. See our multi-user dictionary definition for a complete definition for a complete definition. Below are some examples of multi-user Operating Systems.
Linux
Unix
Windows 2000
Windows XP
Mac OS X

Multiprocessing – An Operating System capable of supporting and utilizing more than one computer processor. Below are some examples of multiprocessing Operating Systems.
Linux
Unix
Windows 2000
Windows XP
Mac OS X

Multitasking – An Operating system that is capable of allowing multiple software processes to run at the same time. Below are some examples of multitasking Operating Systems.
Unix
Windows 2000
Windows XP
Mac OS X

Multithreading – Operating systems that allow different parts of a software program to run concurrently. Operating systems that would fall into this category are:
Linux
Unix
Windows 2000
Windows XP
Mac OS X

Linux


Of the following technologies, which is considered a client-side script? A) JavaScript B) Java C) ASP D) C++

Answer: A – JavaScript is the only client-side script listed. Java and C++ are complete programming languages. Active Server Pages are parsed on the server with the results being sent to the client in HTML

What is the name and path of the main system log?

Answer: /var/log/messages
By default, the main system log is /var/log/messages.

What is the minimum number of partitions you need to install Linux?

Answer: 2
Linux can be installed on two partitions, one as / which will contain all files and a swap partition.

What command can you use to review boot messages?

Answer: dmesg
The dmesg command displays the system messages contained in the kernel ring buffer. By using this command immediately after booting your computer, you will see the boot messages.

In order to display the last five commands you have entered using the history command, you would type ___________ .

Answer: history 5
The history command displays the commands you have previously entered. By passing it an argument of 5, only the last five commands will be displayed.

What utility can you use to automate rotation of logs?

Answer: logrotate
The logrotate command can be used to automate the rotation of various logs.

When planning your backup strategy you need to consider how often you will perform a backup, how much time the backup takes and what media you will use. What other factor must you consider when planning your backup strategy? _________

what to backup
Choosing which files to backup is the first step in planning your backup strategy.

Which partitions might you create on the mail server’s hard drive(s) other than the root, swap, and boot partitions? [Choose all correct answers] A) /var/spool B) /tmp C) /proc D) /bin E) /home

Answer(s): A, B, E – Separating /var/spool onto its own partition helps to ensure that if something goes wrong with the mail server or spool, the output cannot overrun the file system. Putting /tmp on its own partition prevents either software or user items in the /tmp directory from overrunning the file system. Placing /home off on its own is mostly useful for system re-installs or upgrades, allowing you to not have to wipe the /home hierarchy along with other areas. Answers c and d are not possible, as the /proc portion of the file system is virtual-held in RAM-not placed on the hard drives, and the /bin hierarchy is necessary for basic system functionality and, therefore, not one that you can place on a different partition.

Which partitioning tool is available in all distributions? A) Disk Druid B) fdisk C) Partition Magic D) FAT32 E) System Commander

Answer(s): B – The fdisk partitioning tool is available in all Linux distributions. Answers a, c, and e all handle partitioning, but do not come with all distributions. Disk Druid is made by Red Hat and used in its distribution along with some derivatives. Partition Magic and System Commander are tools made by third-party companies. Answer d is not a tool, but a file system type. Specifically, FAT32 is the file system type used in Windows 98.


Which two commands can you use to delete directories? A) rm B) rm -rf C) rmdir D) rd E) rd -rf

Answer(s): B, C – You can use rmdir or rm -rf to delete a directory. Answer a is incorrect, because the rm command without any specific flags will not delete a directory, it will only delete files. Answers d and e point to a non-existent command.

Which file defines all users on your system? Choose one: a. /etc/passwd b. /etc/users c. /etc/password d. /etc/user.conf

Answer: a
The /etc/passwd file contains all the information on users who may log into your system. If a user account is not contained in this file, then the user cannot log in.

You wish to print the file vacations with 60 lines to a page. Which of the following commands will accomplish this? Choose one: a. pr -l60 vacations | lpr b. pr -f vacations | lpr c. pr -m vacations | lpr d. pr -l vacations | lpr

Answer: a
The default page length when using pr is 66 lines. The -l option is used to specify a different length.

You issue the following command useradd -m bobm But the user cannot logon. What is the problem? Choose one: a. You need to assign a password to bobm’s account using the passwd command. b. You need to create bobm’s home directory and set the appropriate permissions. c. You need to edit the /etc/passwd file and assign a shell for bobm’s account. d. The username must be at least five characters long.

Answer: a
The useradd command does not assign a password to newly created accounts. You will still need to use the passwd command to assign a password.

Which of the following tasks is not necessary when creating a new user by editing the /etc/passwd file? Choose one: a. Create a link from the user’s home directory to the shell the user will use. b. Create the user’s home directory c. Use the passwd command to assign a password to the account. d. Add the user to the specified group.

Answer: a
There is no need to link the user’s home directory to the shell command. Rather, the specified shell must be present on your system.

You have a directory called /home/ben/memos and want to move it to /home/bob/memos so you issue the command mv /home/ben/memos /home/bob. What is the results of this action? Choose one: a. The files contained in /home/ben/memos are moved to the directory /home/bob/memos/memos. b. The files contained in /home/ben/memos are moved to the directory /home/bob/memos. c. The files contained in /home/ben/memos are moved to the directory /home/bob/. d. The command fails since a directory called memos already exists in the target directory.

Answer: a
When using the mv command to move a directory, if a directory of the same name exists then a subdirectory is created for the files to be moved.

In order to prevent a user from logging in, you can add a(n) ________at the beginning of the password fi

Answer: asterick
If you add an asterick at the beginning of the password field in the /etc/passwd file, that user will not be able to log in.

Which of the following commands will show a list of the files in your home directory including hidden files and the contents of all subdirectories? Choose one: a. ls -c home b. ls -aR /home/username c. ls -aF /home/username d. ls -l /home/username

Answer: b
The ls command is used to display a listing of files. The -a option will cause hidden files to be displayed as well. The -R option causes ls to recurse down the directory tree. All of this starts at your home directory.

There are seven fields in the /etc/passwd file. Which of the following lists all the fields in the correct order? Choose one: a. username, UID, GID, home directory, command, comment b. username, UID, GID, comment, home directory, command c. UID, username, GID, home directory, comment, command d. username, UID, group name, GID, home directory, comment

Answer: b
The seven fields required for each line in the /etc/passwd file are username, UID, GID, comment, home directory, command. Each of these fields must be separated by a colon even if they are empty.

While logged on as a regular user, your boss calls up and wants you to create a new user account immediately. How can you do this without first having to close your work, log off and logon as root? Choose one: a. Issue the command rootlog. b. Issue the command su and type exit when finished. c. Issue the command su and type logoff when finished. d. Issue the command logon root and type exit when finished.

Answer: b
You can use the su command to imitate any user including root. You will be prompted for the password for the root account. Once you have provided it you are logged in as root and can do any administrative duties.

What command allows you to set a processor-intensive job to use less CPU time? A) ps B) nice C) chps D) less E) more

Answer: B – The nice command is used to change a job’s priority level, so that it runs slower or faster. Answers a, d, and e are valid commands but are not used to change process information. Answer c is an invalid command.

What file would you edit in your home directory to change which window manager you want to use? A) Xinit B) .xinitrc C) XF86Setup D) xstart E) xf86init

Answer: B – The ~/.xinitrc file allows you to set which window man-ager you want to use when logging in to X from that account.
Answers a, d, and e are all invalid files. Answer c is the main X server configuration file.

When you install a new application, documentation on that application is also usually installed. Where would you look for the documentation after installing an application called MyApp? Choose one: a. /usr/MyApp b. /lib/doc/MyApp c. /usr/doc/MyApp d. In the same directory where the application is installed.

c
The default location for application documentation is in a directory named for the application in the /usr/doc directory.




You attempt to use shadow passwords but are unsuccessful. What characteristic of the /etc/passwd file may cause this? Choose one: a. The login command is missing. b. The username is too long. c. The password field is blank. d. The password field is prefaced by an asterisk.

c
The password field must not be blank before converting to shadow passwords.

You want to enter a series of commands from the command-line. What would be the quickest way to do this? Choose One a. Press enter after entering each command and its arguments b. Put them in a script and execute the script c. Separate each command with a semi-colon (;) and press enter after the last command d. Separate each command with a / and press enter after the last command

c
The semi-colon may be used to tell the shell that you are entering multiple commands that should be executed serially. If these were commands that you would frequently want to run, then a script might be more efficient. However, to run these commands only once, enter the commands directly at the command line.

When using useradd to create a new user account, which of the following tasks is not done automatically. Choose one: a. Assign a UID. b. Assign a default shell. c. Create the user’s home directory. d. Define the user’s home directory.

c
The useradd command will use the system default for the user’s home directory. The home directory is not created, however, unless you use the -m option.

Which password package should you install to ensure that the central password file couldn’t be stolen easily? A) PAM B) tcp_wrappers C) shadow D) securepass E) ssh

C – The shadow password package moves the central password file to a more secure location. Answers a, b, and e all point to valid packages, but none of these places the password file in a more secure location. Answer d points to an invalid package.

What type of server is used to remotely assign IP addresses to machines during the installation process? A) SMB B) NFS C) DHCP D) FT E) HTTP

C – You can use a DHCP server to assign IP addresses to individual machines during the installation process. Answers a, b, d, and e list legitimate Linux servers, but these servers do not provide IP addresses. The SMB, or Samba, tool is used for file and print sharing across multi-OS networks. An NFS server is for file sharing across Linux net-works. FTP is a file storage server that allows people to browse and retrieve information by logging in to it, and HTTP is for the Web.

The easiest, most basic form of backing up a file is to _____ it to another location.

copy
The easiest most basic form of backing up a file is to make a copy of that file to another location such as a floppy disk.

What key combination can you press to suspend a running job and place it in the background?

ctrl-z
Using ctrl-z will suspend a job and put it in the background.

When you create a new partition, you need to designate its size by defining the starting and ending _____________.

cylinders
When creating a new partition you must first specify its starting cylinder. You can then either specify its size or the ending cylinder.
By on | Linux | 2 comments

allquestions.co.in 2010.  WikiWP theme, powered by Chereshka & WordPress.   |   RSS

You have a new application on a CD-ROM that you wish to install. What should your first step be? Choose one: a. Read the installation instructions on the CD-ROM. b. Use the mount command to mount your CD-ROM as read-write. c. Use the umount command to access your CD-ROM. d. Use the mount command to mount your CD-ROM as read-only.

d
Before you can read any of the files contained on the CD-ROM, you must first mount the CD-ROM.

You have the /var directory on its own partition. You have run out of space. What should you do? Choose one: a. Reconfigure your system to not write to the log files. b. Use fips to enlarge the partition. c. Delete all the log files. d. Delete the partition and recreate it with a larger size.

d
The only way to enlarge a partition is to delete it and recreate it. You will then have to restore the necessary files from backup.

You are covering for another system administrator and one of the users asks you to restore a file for him. You locate the correct tarfile by checking the backup log but do not know how the directory structure was stored. What command can you use to determine this? Choose one: a. tar fx tarfile dirname b. tar tvf tarfile filename c. tar ctf tarfile d. tar tvf tarfile

d
The t switch will list the files contained in the tarfile. Using the v modifier will display the stored directory structure.

If you type the command cat dog & > cat what would you see on your display? Choose one: a. Any error messages only. b. The contents of the file dog. c. The contents of the file dog and any error messages. d. Nothing as all output is saved to the file cat.

d
When you use & > for redirection, it redirects both the standard output and standard error. The output would be saved to the file cat.

What type of local file server can you use to provide the distribution installation materials to the new machine during a network installation? A) Inetd B) FSSTND C) DNS D) NNTP E) NFS

E – You can use an NFS server to provide the distribution installation materials to the machine on which you are performing the installation. Answers a, b, c, and d are all valid items but none of them are file servers. Inetd is the superdaemon which controls all intermittently used network services. The FSSTND is the Linux File System Standard. DNS provides domain name resolution, and NNTP is the transfer protocol for usenet news.

What can you type at a command line to determine which shell you are using?

echo $SHELL
The name and path to the shell you are using is saved to the SHELL environment variable. You can then use the echo command to print out the value of any variable by preceding the variable’s name with $. Therefore, typing echo $SHELL will display the name of your shell.

What command would you type to use the cpio to create a backup called backup.cpio of all the users’ home directories?

find /home | cpio -o > backup.cpio
The find command is used to create a list of the files and directories contained in home. This list is then piped to the cpio utility as a list of files to include and the output is saved to a file called backup.cpio.

What command is used to remove the password assigned to a group?

gpasswd -r
The gpasswd command is used to change the password assigned to a group. Use the -r option to remove the password from the group.

What file defines the levels of messages written to system log files?

kernel.h
To determine the various levels of messages that are defined on your system, examine the kernel.h file.

What command should you type to see all the files with an extension of ‘mem’ listed in reverse alphabetical order in the /home/ben/memos directory.

ls -r /home/ben/memos/*.mem
The -c option used with ls results in the files being listed in chronological order. You can use wildcards with the ls command to specify a pattern of filenames.

The top utility can be used to change the priority of a running process? Another utility that can also be used to change priority is ___________?

nice
Both the top and nice utilities provide the capability to change the priority of a running process.

Bob Armstrong, who has a username of boba, calls to tell you he forgot his password. What command should you use to reset his command?

passwd boba
The passwd command is used to change your password. If you do not specify a username, your password will be changed.

In order to improve your system’s security you decide to implement shadow passwords. What command should you use?

pwconv
The pwconv command creates the file /etc/shadow and changes all passwords to ‘x’ in the /etc/passwd file.

In order to run fsck on the root partition, the root partition must be mounted as

readonly
You cannot run fsck on a partition that is mounted as read-write.

What command should you use to check the number of files and disk space used and each user’s defined quotas?

repquota
The repquota command is used to get a report on the status of the quotas you have set including the amount of allocated space and amount of used space.

What account is created when you install Linux?

root
Whenever you install Linux, only one user account is created. This is the superuser account also known as root.

You would like to temporarily change your command line editor to be vi. What command should you type to change it?

set -o vi
The set command is used to assign environment variables. In this case, you are instructing your shell to assign vi as your command line editor. However, once you log off and log back in you will return to the previously defined command line editor.

You have a file called phonenos that is almost 4,000 lines long. What text filter can you use to split it into four pieces each 1,000 lines long?

split
The split text filter will divide files into equally sized pieces. The default length of each piece is 1,000 lines.

What daemon is responsible for tracking events on your system?

syslogd
The syslogd daemon is responsible for tracking system information and saving it to specified log files.

You want to create a compressed backup of the users’ home directories. What utility should you use?

tar
You can use the z modifier with tar to compress your archive at the same time as creating it.

You need to view the contents of the tarfile called MyBackup.tar. What command would you use?

tar tf MyBackup.tar
The t switch tells tar to display the contents and the f modifier specifies which file to examine.

You wish to restore the file memo.ben which was backed up in the tarfile MyBackup.tar. What command should you type?

tar xf MyBackup.tar memo.ben
This command uses the x switch to extract a file. Here the file memo.ben will be restored from the tarfile MyBackup.tar.

Where is standard output usually directed?

to the screen or display
By default, your shell directs standard output to your screen or display.

What utility can you use to show a dynamic listing of running processes? __________

top
The top utility shows a listing of all running processes that is dynamically updated.

When you issue the command ls -l, the first character of the resulting display represents the file’s ___________.

type
The first character of the permission block designates the type of file that is being displayed.

You locate a command in the /bin directory but do not know what it does. What command can you use to determine its purpose.

whatis
The whatis command displays a summary line from the man page for the specified command.

You suspect that you have two commands with the same name as the command is not producing the expected results. What command can you use to determine the location of the command being run?

which
The which command searches your path until it finds a command that matches the command you are looking for and displays its full path.

You routinely compress old log files. You now need to examine a log from two months ago. In order to view its contents without first having to decompress it, use the _________ utility.

zcat

Who owns the data dictionary?

The SYS user owns the data dictionary. The SYS and SYSTEM users are created when the database is created.

You need to see the last fifteen lines of the files dog, cat and horse. What command should you use?

tail -15 dog cat horse
The tail utility displays the end of a file. The -15 tells tail to display the last fifteen lines of each specified file. 

C Programming

When the network service built-in account connects to a network resource, what is the context?
The computer account of the Windows installation.
The network service account connects to network resources as the computer account for the Windows installation.

What type of connectivity does the readpipe/makepipe utility test?

Named Pipes
The readpipe and makepipe utility combination will test named pipe connectivity.

What are the standard predefined macros ?

The ANSI C standard defines six predefined macros for use in the C language:
Macro Name Purpose

_ _LINE_ _ Inserts the current source code line number in your code.
_ _FILE_ _ Inserts the current source code filename in your code.
_ _ Inserts the current date of compilation in your code.
_ _TIME_ _ Inserts the current time of compilation in your code.
_ _STDC_ _ Is set to 1 if you are enforcing strict ANSI C conformity.
_ _cplusplus Is defined if you are compiling a C++ program.

Is it better to use a macro or a function ?

The answer depends on the situation you are writing code for. Macros have the distinct advantage of being more efficient (and faster) than functions, because their corresponding code is inserted directly into your source code at the point where the macro is called.
There is no overhead involved in using a macro like there is in placing a call to a function. However, macros are generally small and cannot handle large, complex coding constructs.
A function is more suited for this type of situation. Additionally, macros are expanded inline, which means that the code is replicated for each occurrence of a macro. Your code therefore could be somewhat larger when you use macros than if you were to use functions.
Thus, the choice between using a macro and using a function is one of deciding between the tradeoff of faster program speed versus smaller program size. Generally, you should use macros to replace small, repeatable code sections, and you should use functions for larger coding tasks that might require several lines of code.

What is the easiest sorting method to use ?

The answer is the standard library function qsort(). It’s the easiest sort by far for several reasons:
It is already written.
It is already debugged.
It has been optimized as much as possible (usually).

Void qsort(void *buf, size_t num, size_t size, int (*comp)(const void *ele1, const void *ele2));

What will the preprocessor do for a program ?

The C preprocessor is used to modify your program according to the preprocessor directives in your source code. A preprocessor directive is a statement (such as #define) that gives the preprocessor specific instructions on how to modify your source code.
The preprocessor is invoked as the first part of your compiler program’s compilation step. It is usually hidden from the programmer because it is run automatically by the compiler.
The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code. This preprocessed version has all of its macros and constant symbols replaced by their corresponding code and value assignments.
If your source code contains any conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly.

Home > C Interview Questions > Why n++ executes faster than n+1 ? The expression n++ requires a single machine instruction such as INR to carry out the increment operation whereas, n+1 requires more instructions to carry out this operation. Have a Question ? post your questions here. It will be answered as soon as possible.

Home > C Interview Questions >
Why n++ executes faster than n+1 ?

The expression n++ requires a single machine instruction such as INR to carry out the increment operation whereas, n+1 requires more instructions to carry out this operation.
Have a Question ? post your questions here. It will be answered as soon as possible.

What is the purpose of main( ) function ?

The function main( ) invokes other functions within it.It is the first function to be called when the program starts execution.
*
It is the starting function
*

It returns an int value to the environment that called the program
*

Recursive call is allowed for main( ) also.
*

It is a user-defined function
*

Program execution ends when the closing brace of the function main( ) is reached.
*

It has two arguments 1)argument count and 2) argument vector (represents strings passed).
*

Any user-defined name can also be used as parameters for main( ) instead of argc and argv

How do you use a pointer to a function ?

The hardest part about using a pointer-to-function is declaring it.
Consider an example. You want to create a pointer, pf, that points to the strcmp() function.

The strcmp() function is declared in this way:
int strcmp(const char *, const char * )

To set up pf to point to the strcmp() function, you want a declaration that looks just like the strcmp() function’s declaration, but that has *pf rather than strcmp:
int (*pf)( const char *, const char * );

After you’ve gotten the declaration of pf, you can #include and assign the address of strcmp() to pf: pf = strcmp;

What is the heap ?

The heap is where malloc(), calloc(), and realloc() get memory.
Getting memory from the heap is much slower than getting it from the stack. On the other hand, the heap is much more flexible than the stack. Memory can be allocated at any time and deallocated in any order. Such memory isn’t deallocated automatically; you have to call free().
Recursive data structures are almost always implemented with memory from the heap. Strings often come from there too, especially strings that could be very long at runtime.
If you can keep data in a local variable (and allocate it from the stack), your code will run faster than if you put the data on the heap. Sometimes you can use a better algorithm if you use the heap faster, or more robust, or more flexible.
It’s a tradeoff. If memory is allocated from the heap, it’s available until the program ends. That’s great if you remember to deallocate it when you’re done. If you forget, it’s a problem.
A memory leak is some allocated memory that’s no longer needed but isn’t deallocated. If you have a memory leak inside a loop, you can use up all the memory on the heap and not be able to get any more. (When that happens, the allocation functions return a null pointer.)
In some environments, if a program doesn’t deallocate everything it allocated, memory stays unavailable even after the program ends.

What is the purpose of realloc( ) ?

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 n specifies the new size.
The size may be increased or decreased. If n is greater than the old size and if sufficient space is not available subsequent to the old region, the function realloc( ) may create a new region and all the old data are moved to the new region.

How can you restore a redirected standard stream ?

The preceding example showed how you can redirect a standard stream from within your program. But what if later in your program you wanted to restore the standard stream to its original state?
By using the standard C library functions named dup() and fdopen(), you can restore a standard stream such as stdout to its original state.
The dup() function duplicates a file handle. You can use the dup() function to save the file handle corresponding to the stdout standard stream.
The fdopen() function opens a stream that has been duplicated with the dup() function.

What is Preprocessor ?

The preprocessor is used to modify your program according to the preprocessor directives in your source code.
Preprocessor directives (such as #define) give the preprocessor specific instructions on how to modify your source code. The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code.
This preprocessed version has all of its macros and constant symbols replaced by their corresponding code and value assignments. If your source code contains any conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly.
The preprocessor contains many features that are powerful to use, such as creating macros, performing conditional compilation, inserting predefined environment variables into your code, and turning compiler features on and off.
For the professional programmer, in-depth knowledge of the features of the preprocessor can be one of the keys to creating fast, efficient programs.


Can a file other than a .h file be included with #include?
The preprocessor will include whatever file you specify in your #include statement. Therefore, if you have the line
#include
in your program, the file macros.inc will be included in your precompiled program. It is, however, unusual programming practice to put any file that does not have a .h or .hpp extension in an #include statement.
You should always put a .h extension on any of your C files you are going to include. This method makes it easier for you and others to identify which files are being used for preprocessing purposes.
For instance, someone modifying or debugging your program might not know to look at the macros.inc file for macro definitions. That person might try in vain by searching all files with .h extensions and come up empty.
If your file had been named macros.h, the search would have included the macros.h file, and the searcher would have been able to see what macros you defined in it.

How do you print an address?

The safest way is to use printf() (or fprintf() or sprintf()) with the %P specification. That prints a void pointer (void*). Different compilers might print a pointer with different formats.
Your compiler will pick a format that’s right for your environment.
If you have some other kind of pointer (not a void*) and you want to be very safe, cast the pointer to a void*:

printf( %Pn, (void*) buffer );

What is the stack?

The stack is where all the functions’ local (auto) variables are created. The stack also contains some information used to call and return from functions.
A stack trace is a list of which functions have been called, based on this information. When you start using a debugger, one of the first things you should learn is how to get a stack trace.
The stack is very inflexible about allocating memory; everything must be deallocated in exactly the reverse order it was allocated in. For implementing function calls, that is all that’s needed. Allocating memory off the stack is extremely efficient. One of the reasons C compilers generate such good code is their heavy use of a simple stack.
There used to be a C function that any programmer could use for allocating memory off the stack. The memory was automatically deallocated when the calling function returned. This was a dangerous function to call; it’s not available anymore.

Is it possible to execute code even after the program exits the main() function ?

The standard C library provides a function named atexit() that can be used to perform cleanup operations when your program terminates.
You can set up a set of functions you want to perform automatically when your program exits by passing function pointers to the at exit() function.

How can I convert a number to a string?

The standard C library provides several functions for converting numbers of all formats (integers, longs, floats, and so on) to strings and vice versa
The following functions can be used to convert integers to strings:
Function Name Purpose

itoa() Converts an integer value to a string.
ltoa() Converts a long integer value to a string.
ultoa() Converts an unsigned long integer value to a string.
The following functions can be used to convert floating-point values to strings:

Function Name Purpose
ecvt() Converts a double-precision floating-point value to a string without an embedded decimal point.
fcvt() Same as ecvt(), but forces the precision to a specified number of digits.
gcvt() Converts a double-precision floating-point value to a string with an embedded decimal point.

How can I convert a string to a number?

The standard C library provides several functions for converting strings to numbers of all formats (integers, longs, floats, and so on) and vice versa.
The following functions can be used to convert strings to numbers:
Function Name Purpose

atof() Converts a string to a double-precision floating-point value.
atoi() Converts a string to an integer.
atol() Converts a string to a long integer.
strtod() Converts a string to a double-precision floating-point value and reports any leftover numbers that could not be converted.
strtol() Converts a string to a long integer and reports any leftover numbers that could not be converted.
strtoul() Converts a string to an unsigned long integer and reports any leftover numbers that could not be converted.

What is the difference between a string copy (strcpy) and a memory copy (memcpy)? When should each be used?

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 () 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 number of bytes you want to copy from the source to the destination.

When should a type cast be used ?

There are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly.
The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers.
For example, the following line type casts the return value of the call to malloc() to be a pointer to a foo structure.
struct foo *p = (struct foo *) malloc(sizeof(struct foo));

What is a null pointer assignment error? What are bus errors, memory faults, and core dumps ?

These are all serious errors, symptoms of a wild pointer or subscript.
Null pointer assignment is a message you might get when an MS-DOS program finishes executing. Some such programs can arrange for a small amount of memory to be available “where the NULL pointer points to (so to speak).

If the program tries to write to that area, it will overwrite the data put there by the compiler.
When the program is done, code generated by the compiler examines that area. If that data has been changed, the compiler-generated code complains with null pointer assignment.
This message carries only enough information to get you worried. There’s no way to tell, just from a null pointer assignment message, what part of your program is responsible for the error. Some debuggers, and some compilers, can give you more help in finding the problem.
Bus error: core dumped and Memory fault: core dumped are messages you might see from a program running under UNIX. They’re more programmer friendly. Both mean that a pointer or an array subscript was wildly out of bounds. You can get these messages on a read or on a write. They aren’t restricted to null pointer problems.
The core dumped part of the message is telling you about a file, called core, that has just been written in your current directory. This is a dump of everything on the stack and in the heap at the time the program was running. With the help of a debugger, you can use the core dump to find where the bad pointer was used.
That might not tell you why the pointer was bad, but it’s a step in the right direction. If you don’t have write permission in the current directory, you won’t get a core file, or the core dumped message

Why should we assign NULL to the elements (pointer) after freeing them ?

This is paranoia based on long experience. After a pointer has been freed, you can no longer use the pointed-to data. The pointer is said to dangle; it doesn’t point at anything useful.
If you NULL out or zero out a pointer immediately after freeing it, your program can no longer get in trouble by using that pointer. True, you might go indirect on the null pointer instead, but that’s something your debugger might be able to help you with immediately.
Also, there still might be copies of the pointer that refer to the memory that has been deallocated; that’s the nature of C. Zeroing out pointers after freeing them won’t solve all problems;


How can I search for data in a linked list ?
Unfortunately, the only way to search a linked list is with a linear search, because the only way a linked list’s members can be accessed is sequentially.
Sometimes it is quicker to take the data from a linked list and store it in a different data structure so that searches can be more efficient.

What is the benefit of using #define to declare a constant ?

Using the #define method of declaring a constant enables you to declare a constant in one place and use it throughout your program. This helps make your programs more maintainable, because you need to maintain only the #define statement and not several instances of individual constants throughout your program.
For instance, if your program used the value of pi (approximately 3.14159) several times, you might want to declare a constant for pi as follows:
#define PI 3.14159
Using the #define method of declaring a constant is probably the most familiar way of declaring constants to traditional C programmers. Besides being the most common method of declaring constants, it also takes up the least memory.
Constants defined in this manner are simply placed directly into your source code, with no variable space allocated in memory. Unfortunately, this is one reason why most debuggers cannot inspect constants created using the #define method.

When does the compiler not implicitly generate the address of the first element of an array ?

Whenever an array name appears in an expression such as
*
array as an operand of the sizeof operator
*

array as an operand of & operator
*

array as a string literal initializer for a character array
Then the compiler does not implicitly generate the address of the address of the first element of an array.

What is page thrashing ?

Some operating systems (such as UNIX or Windows in enhanced mode) use virtual memory. Virtual memory is a technique for making a machine behave as if it had more memory than it really has, by using disk space to simulate RAM (random-access memory).
In the 80386 and higher Intel CPU chips, and in most other modern microprocessors (such as the Motorola 68030, Sparc, and Power PC), exists a piece of hardware called the Memory Management Unit, or MMU.
The MMU treats memory as if it were composed of a series of pages. A page of memory is a block of contiguous bytes of a certain size, usually 4096 or 8192 bytes. The operating system sets up and maintains a table for each running program called the Process Memory Map, or PMM. This is a table of all the pages of memory that program can access and where each is really located.
Every time your program accesses any portion of memory, the address (called a virtual address) is processed by the MMU. The MMU looks in the PMM to find out where the memory is really located (called the physical address). The physical address can be any location in memory or on disk that the operating system has assigned for it. If the location the program wants to access is on disk, the page containing it must be read from disk into memory, and the PMM must be updated to reflect this action (this is called a page fault).
Because accessing the disk is so much slower than accessing RAM, the operating system tries to keep as much of the virtual memory as possible in RAM. If you’re running a large enough program (or several small programs at once), there might not be enough RAM to hold all the memory used by the programs, so some of it must be moved out of RAM and onto disk (this action is called paging out).
The operating system tries to guess which areas of memory aren’t likely to be used for a while (usually based on how the memory has been used in the past). If it guesses wrong, or if your programs are accessing lots of memory in lots of places, many page faults will occur in order to read in the pages that were paged out. Because all of RAM is being used, for each page read in to be accessed, another page must be paged out. This can lead to more page faults, because now a different page of memory has been moved to disk.
The problem of many page faults occurring in a short time, called page thrashing, can drastically cut the performance of a system. Programs that frequently access many widely separated locations in memory are more likely to cause page thrashing on a system. So is running many small programs that all continue to run even when you are not actively using them.
To reduce page thrashing, you can run fewer programs simultaneously. Or you can try changing the way a large program works to maximize the capability of the operating system to guess which pages won’t be needed. You can achieve this effect by caching values or changing lookup algorithms in large data structures, or sometimes by changing to a memory allocation library which provides an implementation of malloc() that allocates memory more efficiently. Finally, you might consider adding more RAM to the system to reduce the need to page out.

Size of an allocated portion of memory

You can’t, really. free() can , but there’s no way for your program to know the trick free() uses. Even if you disassemble the library and discover the trick, there’s no guarantee the trick won’t change with the next release of the compiler.

When should the register modifier be used?

The register modifier hints to the compiler that the variable will be heavily used and should be kept in the CPU’s registers, if possible, so that it can be accessed faster.
There are several restrictions on the use of the register modifier.

First, the variable must be of a type that can be held in the CPU’s register. This usually means a single value of a size less than or equal to the size of an integer. Some machines have registers that can hold floating-point numbers as well.
Second, because the variable might not be stored in memory, its address cannot be taken with the unary & operator. An attempt to do so is flagged as an error by the compiler. Some additional rules affect how useful the register modifier is. Because the number of registers is limited, and because some registers can hold only certain types of data (such as pointers or floating-point numbers), the number and types of register modifiers that will actually have any effect are dependent on what machine the program will run on. Any additional register modifiers are silently ignored by the compiler.
Also, in some cases, it might actually be slower to keep a variable in a register because that register then becomes unavailable for other purposes or because the variable isn’t used enough to justify the overhead of loading and storing it.
So when should the register modifier be used? The answer is never, with most modern compilers. Early C compilers did not keep any variables in registers unless directed to do so, and the register modifier was a valuable addition to the language.
C compiler design has advanced to the point, however, where the compiler will usually make better decisions than the programmer about which variables should be stored in registers.
In fact, many compilers actually ignore the register modifier, which is perfectly legal, because it is only a hint and not a directive.

When should the volatile modifier be used ?

The volatile modifier is a directive to the compiler’s optimizer that operations involving this variable should not be optimized in certain ways. There are two special cases in which use of the volatile modifier is desirable. The first case involves memory-mapped hardware (a device such as a graphics adaptor that appears to the computer’s hardware as if it were part of the computer’s memory), and the second involves shared memory (memory used by two or more programs running simultaneously).
Most computers have a set of registers that can be accessed faster than the computer’s main memory. A good compiler will perform a kind of optimization called redundant load and store removal. The compiler looks for places in the code where it can either remove an instruction to load data from memory because the value is already in a register, or remove an instruction to store data to memory because the value can stay in a register until it is changed again anyway.
If a variable is a pointer to something other than normal memory, such as memory-mapped ports on a peripheral, redundant load and store optimizations might be detrimental. For instance, here’s a piece of code that might be used to time some operation:

time_t time_addition(volatile const struct timer *t, int a)
{
int n;
int x;
time_t then;
x = 0;
then = t->value;
for (n = 0; n < 1000; n++)
{
x = x + a;
}
return t->value – then;
}

In this code, the variable t-> value is actually a hardware counter that is being incremented as time passes. The function adds the value of a to x 1000 times, and it returns the amount the timer was incremented by while the 1000 additions were being performed. Without the volatile modifier, a clever optimizer might assume that the value of t does not change during the execution of the function, because there is no statement that explicitly changes it. In that case, there’s no need to read it from memory a second time and subtract it, because the answer will always be 0.
The compiler might therefore optimize the function by making it always return 0.
If a variable points to data in shared memory, you also don’t want the compiler to perform redundant load and store optimizations. Shared memory is normally used to enable two programs to communicate with each other by having one program store data in the shared portion of memory and the other program read the same portion of memory. If the compiler optimizes away a load or store of shared memory, communication between the two programs will be affected.

What is the quickest sorting method to use ?

The answer depends on what you mean by quickest. For most sorting problems, it just doesn’t matter how quick the sort is because it is done infrequently or other operations take significantly more time anyway. Even in cases in which sorting speed is of the essence, there is no one answer. It depends on not only the size and nature of the data, but also the likely order. No algorithm is best in all cases.
There are three sorting methods in this author’s toolbox that are all very fast and that are useful in different situations. Those methods are quick sort, merge sort, and radix sort.

The Quick Sort
The quick sort algorithm is of the divide and conquer type. That means it works by reducing a sorting problem into several easier sorting problems and solving each of them. A dividing value is chosen from the input data, and the data is partitioned into three sets: elements that belong before the dividing value, the value itself, and elements that come after the dividing value. The partitioning is performed by exchanging elements that are in the first set but belong in the third with elements that are in the third set but belong in the first Elements that are equal to the dividing element can be put in any of the three setsthe algorithm will still work properly.

The Merge Sort
The merge sort is a divide and conquer sort as well. It works by considering the data to be sorted as a sequence of already-sorted lists (in the worst case, each list is one element long). Adjacent sorted lists are merged into larger sorted lists until there is a single sorted list containing all the elements. The merge sort is good at sorting lists and other data structures that are not in arrays, and it can be used to sort things that don’t fit into memory. It also can be implemented as a stable sort.
The Radix Sort
The radix sort takes a list of integers and puts each element on a smaller list, depending on the value of its least significant byte. Then the small lists are concatenated, and the process is repeated for each more significant byte until the list is sorted. The radix sort is simpler to implement on fixed-length data such as ints.



What is the benefit of using an enum rather than a #define constant ?
The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.
1) The first advantage is that enumerated constants are generated automatically by the compiler. Conversely, symbolic constants must be manually assigned values by the programmer.
For instance, if you had an enumerated constant type for error codes that could occur in your program, your enum definition could look something like this:
enum Error_Code
{
OUT_OF_MEMORY,
INSUFFICIENT_DISK_SPACE,
LOGIC_ERROR,
FILE_NOT_FOUND
};
In the preceding example, OUT_OF_MEMORY is automatically assigned the value of 0 (zero) by the compiler because it appears first in the definition. The compiler then continues to automatically assign numbers to the enumerated constants, making INSUFFICIENT_DISK_SPACE equal to 1, LOGIC_ERROR equal to 2, and FILE_NOT_FOUND equal to 3, so on.
If you were to approach the same example by using symbolic constants, your code would look something like this:
#define OUT_OF_MEMORY 0
#define INSUFFICIENT_DISK_SPACE 1
#define LOGIC_ERROR 2
#define FILE_NOT_FOUND 3
values by the programmer. Each of the two methods arrives at the same result: four constants assigned numeric values to represent error codes. Consider the maintenance required, however, if you were to add two constants to represent the error codes DRIVE_NOT_READY and CORRUPT_FILE. Using the enumeration constant method, you simply would put these two constants anywhere in the enum definition. The compiler would generate two unique values for these constants. Using the symbolic constant method, you would have to manually assign two new numbers to these constants. Additionally, you would want to ensure that the numbers you assign to these constants are unique.
2) Another advantage of using the enumeration constant method is that your programs are more readable and thus can be understood better by others who might have to update your program later.

3) A third advantage to using enumeration constants is that some symbolic debuggers can print the value of an enumeration constant. Conversely, most symbolic debuggers cannot print the value of a symbolic constant. This can be an enormous help in debugging your program, because if your program is stopped at a line that uses an enum, you can simply inspect that constant and instantly know its value. On the other hand, because most debuggers cannot print #define values, you would most likely have to search for that value by manually looking it up in a header file.

What is the result of using Option Explicit ?

When writing your C program, you can include files in two ways.
The first way is to surround the file you want to include with the angled brackets < and >.
This method of inclusion tells the preprocessor to look for the file in the predefined default location.
This predefined default location is often an INCLUDE environment variable that denotes the path to your include files.
For instance, given the INCLUDE variable
INCLUDE=C:\COMPILER\INCLUDE;S:\SOURCE\HEADERS;
using the #include version of file inclusion, the compiler first checks the
C:\COMPILER\INCLUDE
directory for the specified file. If the file is not found there, the compiler then checks the
S:\SOURCE\HEADERS directory. If the file is still not found, the preprocessor checks the current directory.
The second way to include files is to surround the file you want to include with double quotation marks. This method of inclusion tells the preprocessor to look for the file in the current directory first, then look for it in the predefined locations you have set up. Using the #include file version of file inclusion and applying it to the preceding example, the preprocessor first checks the current directory for the specified file. If the file is not found in the current directory, the C:COMPILERINCLUDE directory is searched. If the file is still not found, the preprocessor checks the S:SOURCEHEADERS directory.
The #include method of file inclusion is often used to include standard headers such as stdio.h or
stdlib.h.
This is because these headers are rarely (if ever) modified, and they should always be read from your compiler’s standard include file directory.
The #include file method of file inclusion is often used to include nonstandard header files that you have created for use in your program. This is because these headers are often modified in the current directory, and you will want the preprocessor to use your newly modified version of the header rather than the older, unmodified version.



Difference between const char* p and char const* p
In const char* p, the character pointed by ‘p’ is constant, so u cant change the value of character pointed by p but u can make ‘p’ refer to some other location.
in char const* p, the ptr ‘p’ is constant not the character referenced by it, so u cant make ‘p’ to reference to any other location but u can change the value of the char pointed by ‘p’.

Why does malloc(0) return valid memory address ? What’s the use ?

malloc(0) does not return a non-NULL under every implementation.
An implementation is free to behave in a manner it finds
suitable, if the allocation size requested is zero. The
implmentation may choose any of the following actions:

* A null pointer is returned.
* The behavior is same as if a space of non-zero size
was requested. In this case, the usage of return
value yields to undefined-behavior.

Notice, however, that if the implementation returns a non-NULL
value for a request of a zero-length space, a pointer to object
of ZERO length is returned! Think, how an object of zero size
should be represented?

For implementations that return non-NULL values, a typical usage
is as follows:

void
func ( void )
{
int *p; /* p is a one-dimensional array,
whose size will vary during the
the lifetime of the program */
size_t c;

p = malloc(0); /* initial allocation */
if (!p)
{
perror (”FAILURE” );
return;
}

/* … */
while (1)
{
c = (size_t) … ; /* Calculate allocation size */
p = realloc ( p, c * sizeof *p );

/* use p, or break from the loop */
/* … */
}
return;
}

Notice that this program is not portable, since an implementation
is free to return NULL for a malloc(0) request, as the C Standard
does not support zero-sized objects.

Does there exist any other function which can be used to convert an integer or a float to a string ?

Some implementations provide a nonstandard function called itoa(), which converts an integer to string.
#include
char *itoa(int value, char *string, int radix);
DESCRIPTION
The itoa() function constructs a string representation of an integer.

PARAMETERS
value:
Is the integer to be converted to string representation.

string:
Points to the buffer that is to hold resulting string.
The resulting string may be as long as seventeen bytes.

radix:
Is the base of the number; must be in the range 2 – 36.

A portable solution exists. One can use sprintf():
char s[SOME_CONST];
int i = 10;
float f = 10.20;

sprintf ( s, “%d %f\n”, i, f );

Does there exist any other function which can be used to convert an integer or a float to a string ?

Some implementations provide a nonstandard function called itoa(), which converts an integer to string.
#include
char *itoa(int value, char *string, int radix);
DESCRIPTION
The itoa() function constructs a string representation of an integer.

PARAMETERS
value:
Is the integer to be converted to string representation.

string:
Points to the buffer that is to hold resulting string.
The resulting string may be as long as seventeen bytes.

radix:
Is the base of the number; must be in the range 2 – 36.

A portable solution exists. One can use sprintf():
char s[SOME_CONST];
int i = 10;
float f = 10.20;

sprintf ( s, “%d %f\n”, i, f );

Which bit wise operator is suitable for putting on a particular bit in a number ?

The bitwise OR operator. In the following code snippet, the bit number 24 is turned ON:
some_int = some_int | KBit24;

Which bit wise operator is suitable for turning off a particular bit in a number?

The bitwise AND operator, again. In the following code snippet, the bit number 24 is reset to zero.
some_int = some_int & ~KBit24;

Which bit wise operator is suitable for checking whether a particular bit is on or off ?

The bitwise AND operator. Here is an example:
enum {
KBit0 = 1,
KBit1,

KBit31,
};

if ( some_int & KBit24 )
printf ( “Bit number 24 is ON\n” );
else
printf ( “Bit number 24 is OFF\n” );

Write down the equivalent pointer expression for referring the same element a[i][j][k][l] ?

a[i] == *(a+i)
a[i][j] == *(*(a+i)+j)
a[i][j][k] == *(*(*(a+i)+j)+k)
a[i][j][k][l] == *(*(*(*(a+i)+j)+k)+l)

What is the difference between strings and character arrays ?

A major difference is: string will have static storage duration, whereas as a character array will not, unless it is explicity specified by using the static keyword.
Actually, a string is a character array with following properties:
* the multibyte character sequence, to which we generally call string, is used to initialize an array of static storage duration. The size of this array is just sufficient to contain these characters plus the terminating NUL character.
* it not specified what happens if this array, i.e., string, is modified.
* Two strings of same value[1] may share same memory area. For example, in the following declarations:
char *s1 = “Calvin and Hobbes”;
char *s2 = “Calvin and Hobbes”;

the strings pointed by s1 and s2 may reside in the same memory location. But, it is not true for the following:
char ca1[] = “Calvin and Hobbes”;
char ca2[] = “Calvin and Hobbes”;

[1] The value of a string is the sequence of the values of the contained characters, in order.

Advantages of a macro over a function ?

Macro gets to see the Compilation environment, so it can expand __ __TIME__ __FILE__ #defines. It is expanded by the preprocessor.
For example, you can’t do this without macros
#define PRINT(EXPR) printf( #EXPR “=%d\n”, EXPR)

PRINT( 5+6*7 ) // expands into printf(”5+6*7=%d”, 5+6*7 );
You can define your mini language with macros:
#define strequal(A,B) (!strcmp(A,B))

Macros are a necessary evils of life. The purists don’t like them, but without it no real work gets done.

How to reduce a final size of executable ?

Size of the final executable can be reduced using dynamic linking for libraries.

What is the difference between printf() and sprintf() ?

sprintf() writes data to the character array whereas printf(…) writes data to the standard output device.

What is the difference between calloc() and malloc() ?

1. calloc(…) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0. The total number of memory allocated will be (number_of_elements * size).
malloc(…) takes in only a single argument which is the memory required in bytes. malloc(…) allocated bytes of memory and not blocks of memory like calloc(…).
2. malloc(…) allocates memory blocks and returns a void pointer to the allocated space, or NULL if there is insufficient memory available.
calloc(…) allocates an array in memory with elements initialized to 0 and returns a pointer to the allocated space. calloc(…) calls malloc(…) in order to use the C++ _set_new_mode function to set the new handler mode.

What is the output of printf(“%d”) ?

1. When we write printf(“%d”,x); this means compiler will print the value of x. But as here, there is nothing after %d so compiler will show in output window garbage value.
2. When we use %d the compiler internally uses it to access the argument in the stack (argument stack). Ideally compiler determines the offset of the data variable depending on the format specification string. Now when we write printf(“%d”,a) then compiler first accesses the top most element in the argument stack of the printf which is %d and depending on the format string it calculated to offset to the actual data variable in the memory which is to be printed. Now when only %d will be present in the printf then compiler will calculate the correct offset (which will be the offset to access the integer variable) but as the actual data object is to be printed is not present at that memory location so it will print what ever will be the contents of that memory location.
3. Some compilers check the format string and will generate an error without the proper number and type of arguments for things like printf(…) and scanf(…).
malloc()

What is a null pointer?

There are times when it’s necessary to have a pointer that doesn’t point to anything. The macro NULL, defined in , has a value that’s guaranteed to be different from any valid pointer. NULL is a literal zero, possibly cast to void* or char*.
Some people, notably C++ programmers, prefer to use 0 rather than NULL.
The null pointer is used in three ways:
1) To stop indirection in a recursive data structure.
2) As an error value.
3) As a sentinel value.

Can include files be nested?

Yes. Include files can be nested any number of times. As long as you use precautionary measures , you can avoid including the same file twice. In the past, nesting header files was seen as bad programming practice, because it complicates the dependency tracking function of the MAKE program and thus slows down compilation. Many of today’s popular compilers make up for this difficulty by implementing a concept called precompiled headers, in which all headers and associated dependencies are stored in a precompiled state.
Many programmers like to create a custom header file that has #include statements for every header needed for each module. This is perfectly acceptable and can help avoid potential problems relating to #include files, such as accidentally omitting an #include file in a module.

Can a variable be both constant and volatile?

Yes. The const modifier means that this code cannot change the value of the variable, but that does not mean that the value cannot be changed by means outside this code. For instance, in the example in FAQ 8, the timer structure was accessed through a volatile const pointer.
The function itself did not change the value of the timer, so it was declared const. However, the value was changed by hardware on the computer, so it was declared volatile. If a variable is both const and volatile, the two modifiers can appear in either order.

Can static variables be declared in a header file ?

You can’t declare a static variable without defining it as well (this is because the storage class modifiers static and extern are mutually exclusive). A static variable can be defined in a header file, but this would cause each source file that included the header file to have its own private copy of the variable, which is probably not what was intended.

What is hashing?

To hash means to grind up, and that’s essentially what hashing is all about. The heart of a hashing algorithm is a hash function that takes your nice, neat data and grinds it into some random-looking integer.
The idea behind hashing is that some data either has no inherent ordering (such as images) or is expensive to compare (such as images). If the data has no inherent ordering, you can’t perform comparison searches.
If the data is expensive to compare, the number of comparisons used even by a binary search might be too many. So instead of looking at the data themselves, you’ll condense (hash) the data to an integer (its hash value) and keep all the data with the same hash value in the same place. This task is carried out by using the hash value as an index into an array.
To search for an item, you simply hash it and look at all the data whose hash values match that of the data you’re looking for. This technique greatly lessens the number of items you have to look at. If the parameters are set up with care and enough storage is available for the hash table, the number of comparisons needed to find an item can be made arbitrarily close to one.
One aspect that affects the efficiency of a hashing implementation is the hash function itself. It should ideally distribute data randomly throughout the entire hash table, to reduce the likelihood of collisions. Collisions occur when two different keys have the same hash value.
There are two ways to resolve this problem. In open addressing, the collision is resolved by the choosing of another position in the hash table for the element inserted later. When the hash table is searched, if the entry is not found at its hashed position in the table, the search continues checking until either the element is found or an empty position in the table is found.
The second method of resolving a hash collision is called chaining. In this method, a bucket or linked list holds all the elements whose keys hash to the same value. When the hash table is searched, the list must be searched linearly.

What are the different storage classes in C ?

C has three types of storage: automatic, static and allocated.
Variable having block scope and without static specifier have automatic storage duration.
Variables with block scope, and with static specifier have static scope. Global variables (i.e, file scope) with or without the the static specifier also have static scope.
Memory obtained from calls to malloc(), alloc() or realloc() belongs to allocated storage class.

What does static variable mean?

There are 3 main uses for the static.
1. If you declare within a function:
It retains the value between function calls

2.If it is declared for a function name:
By default function is extern..so it will be visible from other files if the function declaration is as static..it is invisible for the outer files

3. Static for global variables:
By default we can use the global variables from outside files If it is static global..that variable is limited to with in the file.
#include

int t = 10;
main(){
int x = 0;
void funct1();
funct1();
printf(“After first call \n”);
funct1();
printf(“After second call \n”);
funct1();
printf(“After third call \n”);

}
void funct1()
{
static int y = 0;
int z = 10;
printf(“value of y %d z %d”,y,z);
y=y+10;
}

value of y 0 z 10 After first call
value of y 10 z 10 After second call
value of y 20 z 10 After third call



What is C language ?
The C programming language is a standardized programming language developed in the early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system. It has since spread to many other operating systems, and is one of the most widely used programming languages. C is prized for its efficiency, and is the most popular programming language for writing system software, though it is also used for writing applications.