Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Q & A From C, C++, Linux, VxWorks

You are on page 1of 38

1 PART 1

Q & A from C, C++, Linux, VXworks


1)What is Tux Who coined word Tux When Tux got its name Tux what is the acronym of Tux A)Tux is the official mascot of the Linux operating system. Tux, created by Larry Ewing in 1996, is a chubby penguin that looks content and satisfied. The concept of the Linux mascot being a penguin came from Linus Torvalds, the creator of the Linux kernel. It is sometimes claimed that the name was derived from Torvalds UniX, a name suggested by James Hughes, rather than the explanation that penguins look vaguely as if they are wearing a tuxedo. 2) write a C code that executes both its if and else part? This is one quick way, main() { if(1) { printf("Inside IF"); goto e; } else { e: ; printf("inside ELSE"); } return 1; } 3) can any one print "hello" word without using any using any function like..printf,fprintf...etc A) #error hello ! int main(void) { return 0; } 4) why in C ,storage location of array starts frm 0th position whereeas in PASCAL it starts frm 1th location? a[0] in C whereas in PASCAL its a[1]. A) Pascal (and some other languages) supports arrays with indices over any arbitrary range (i.e. not just 1based). However this is just syntactic sugar - the underyling array is just a 0-based array at the machine code level. Higher level langauges offer this kind of feature as an aid to the programmer, whereas C is a relatively low level language, with minimal features and frills. You can actually simulate 1-based (or any N-based) arrays in C - it's not too hard. I've done it myself when I needed arrays that had natural indices from -1 to N, e.g. int _array[N + 2]; // underlying storage for array int * const array = &_array[1]; // array has valid indices from -1..N

5) Is it possible to write a C program without main() function? A) theres a way.. in which the main() doesnt appear explicitly.. that is .. u will not find "main()" written anywhere in the program.. but it will be virtually present. hint: use #define and concatenation preprocessor directive... i.e. # # #include <stdio.h> #define decode(s,t,u,m,p,e,d) m##s##u##t #define begin decode(a,n,i,m,a,t,e) begin() { printf("Stumped??\n"); } now dont start screaming, that the main() is indirectly present. i told it beforehand that it would be present virtually but wont appear explicity in the program. Any way main will be present after preprocessing of that code. If u see the preprocessed code it will be like below main() { printf("Stumped??\n"); } Same ans for the above ques: /* hello.c */ # include <stdio.h> void hello ( void ) { printf ( "Hello World\n" ); exit ( 0 ); } cc hello.c -nostartfiles Ignore the warning and execute the a.out 6)wat is the use in studying data structures? A)data structures is mainly used for the manipulation on data the main fields of data structures include trees,searches,sorts,linked lists,hashing & multilevel indexing. all the the above fields help us to store the data in an efficient way without any wastage of memory space. sorts keep our data organised in a sysytematic manner A)purpose of data structure We just dont go to the clasical definition of a Data Structure, to be simple a datastructure is arranging data in some way.. what ever way u arange data that is a datastructure. Practically, we want to maintain information of students in a class and these students are fixed. and they are numbers 1 to n, for this application suitable Datastructure is "Array". Dictonary Application, if at all we use array for maintaing all words information, its takes N times to find the match.

3
For Optimizing this Suitable DS is Binary Tree. all words are added to this binary tree.. so searching in BST is O(log n) For much better solution indexing with binary tree will be better.. 7)How memory is protected in memotry allocation.I mean when we call malloc() like function it allocates memory... hich way that memory is protected mean that any other process not use that memory. A) Each and every process has its own heap area frm where it allocates the memory required in run time.. so there is no point of memory stealing within processes as whenever a process is allocated time by the scheduler its virtual memory is mapped to the physical memory and kernel will maintain which pages of the phy memory are in use.. u can also view it as RAM being partitioned into several sizes and each size belongs to a particular process. so there is nothing like a process using other process's memory. 8) int main() { \\body getch(); return 0; } here return 0; statement returns value 0 to main function. WHAT it means?????can anyone explain it. A) It does not return the value to main, but main returns the value to the OS (or more correct to the calling process) main's return value is used to determine if the program has exited successfully or with an error. Per convention, 0 means no error, values of 1 and above indicate an error or an uneccssfull run. What value is returned on what kind of error/problem is program specific. 9)what is a Dangling pointer? A) I'm sure Wikipedia covers it in more detail, but I'll bite. A pointer is a memory address --- it "points" to another part of memory. Any particular part of memory can either be valid or invalid. If a pointer points to an invalid piece of memory, it is dangling. Dangling pointer From Wikipedia, the free encyclopedia Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type, or to a distinguished null pointer value in languages which support this. Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. As the system may reallocate the previously freed memory to another process, if the original program then dereferences the (now) dangling pointer, unpredictable behavior may result, as the memory may now contain completely different data. This is especially the case if the program writes data to memory pointed by a dangling pointer, as silent corruption of unrelated data may result, leading to subtle bugs that can be extremely difficult to find, or cause segmentation faults (*NIX) or general protection faults (Windows). If the overwritten data is bookkeeping data used by the system's memory allocator, the corruption can cause system instabilities. Wild pointers arise when a pointer is used prior to initialization to some known state, which is possible in some programming languages. They show the same eratic behaviour as dangling pointers, though they are less likely to stay undetected. Avoiding dangling pointer errors A popular technique to avoid dangling pointers is to use smart pointers. A smart pointer typically uses reference counting to reclaim objects. Some other techniques include the tombstones method and the locksand-keys method.

4
One alternative is to use the DieHard memory allocator[1], which virtually eliminates dangling pointer errors, as well as a variety of other memory errors (like invalid and double frees). Another approach is to use the Boehm garbage collector, a conservative garbage collector that replaces standard memory allocation functions in C and C++ with a garbage collector. This approach completely eliminates dangling pointer errors altogether by disabling frees, and reclaiming objects by garbage collection. In languages like Java, dangling pointers cannot occur because there is no mechanism to explicitly deallocate memory. Rather, the garbage collector may deallocate memory, but only when the object is no longer reachable from any references. 10) Stack Doubt #include <stdio.h> void change(){ int buf[1] = {0}; buf[2] += 7; } int main(void) { int i = 45; change(); i = 10; printf("%d", i); return 0; } The above change function is doing some thing, which is making main function printf to print the value of i as 45. I am not able to track how change function is making printf to print i value 45. Can anybody explain what is happening in change function. A) in sunOS it gives 10 where as in linux it gives 45. buf[2] is pointing to return address location of change function. buf[2] += 7 ; incrementing the return address. so it skiping i=10; it seems very calculate skiping....... otherwise changing return address can make the code behaviour unstable !!!! 11) Printf is still like mist for me .. help to clear Friends see and explain void main() { char *p; p = "%d..%d\n"; printf(p+4,65); } it is printing 65 as expected . But problem is how it works.. even printf need argument like string here we are taking address from % symbol (p+4)..If any body is having good explanation for that then please reply. 12) squeeze ur brain int i, n = 20; for (i = 0; i < n; i--) { printf("X"); } By only changing or adding ONLY ONE character to the above code:

Find 3 ways to make the above code print X 20 times! A) @Answer very near int i, n = 20; for (i = 0; i < n; i--) { printf("X"); } the code may be modified like, int i, n = 20; for (i = 0; ~i < n; i--) { printf("X"); } The above code is giving X 21 times... any1 can give the exact answer... i.e. the code which will print the X 20 times... even i m trying.. A) int i, n = 20; for (i = 40; i < n; i--) { printf("X"); } int i, n = 20; for (i = 0; i + n; i--) { printf("X"); } A) int i, n = 20; for (i = 0; i < -n; i--) { printf("X"); } 13) Dyanamic Allocation Is it possible to dynamically allocate memmory without using any of malloc,calloc Or realloc? A)malloc, calloc are all not part of c they are included in a library so i guess it is possible, to have a user defined definition. A) There's also alloca, which does dynamic allocation on the stack. And C99 supports implict dynamic allocation (e.g. variable length arrays). 14) tell me whether every process has it`s own heap area or they all are allocated memory from same heap on request this is an OS-specific detail, but under a normal VM OS such as Unix. Linux, Mac OS X etc, every process has its own virtual memory space, which is typically the maximum available, i.e. 4 Gb on a 32 bit OS, although there may be some system-wide policy which prevents you from allocating the full 4 Gb. 15) how can we say that sizeof() is an opertor and not a function

6
basically wat`s the diff in func and operaor as far as i know both are implemented using function syntax A) sizeof is a compile-time operator. If you write something like this: x = sizeof(int); what actually gets compiled is: x = 4; // or 2 or 8 or whatever, depending on your OS etc One clue that sizeof is not a function is that you can omit the brackets for built-in types, e.g. x = sizeof int; 16) Cost-Reduced swap without a temporary variable void main() { int i=10,j=20; j = i+j-(i=j);//swapping without a temporary variable } 17) can any one print "hello" word without using any using any function like..printf,fprintf...etc A) #error hello ! int main(void) { return 0; } compile it according to the above then u get error error directive hello! then press enter u get FATAL hello.c: hello! on the programming screen . which is the output. 18) /* Insurance of driver - using logical operators */ main( ) { char sex, ms ; int age ; printf ( "Enter age, sex, marital status " ) ; scanf ( "%d %c %c" &age, &sex, &ms ) ; if ( ( ms == 'M') || ( ms == 'U' && sex == 'M' && age > 30 ) || ( ms == 'U' && sex == 'F' && age > 25 ) ) printf ( "Driver is insured" ) ; else printf ( "Driver is not insured" ) ; } 19) a confusion in volatile a read it`s used in case when a variable is probable to be changed from outside the code.....so when used the variable will bw referenced from it`s actual memory location......can u plz give an example where a variable in one code is shown to be changed from outside the code......i m really confused over volatile.

A) volatile - usually a volatile variable will be changed beacse (a) it's shared memory being accessed by two or more processes or threads or (b) it's a variable which wil be accessed both by a foreground task and an interrupt service routine or some kind of callback function or (c) it's a hardware register which will change due to hardware activity (I/O, timers, etc). 20) is alloca() part of standard library or is it a gcc extension i read that library function internally call the system calls with the help of trap instruction can u plz exlpain by an example how the above is done using TRAP instruction. Is scope resolution operator :: permissible in ANSI C to access global variables with the same name as local variables....or are they only available in C++ A) alloca is available with most modern C compilers but I'm not sure if it's part of the C standard. Some architectures use TRAP instructions or software interrupts to make system calls - this is highly architecturespecific though so you can't make any general statements about this. Nomally the programmer does nto care as they will just make standard library calls. The scope resolution operator :: is only available in C++. 21) struct struct temp { int i; float f; }; //now struct temp *ptr=(struct temp*)malloc(sizeof(struct temp)+4); free(ptr); now how much memory will get freed 1 struct temp avriable total allocated actually this wld be more vcleareer if u plz tell me wat does the ammloc keep to keep the count for amount of memory allocated.....no of objects of the data type or no of bytes of memory alloacted A) malloc doesn't know anything about what you're allocating apart form the size in bytes, so in your example you're probably allocating and freeing 12 bytes (although it's OS-specific, so it may be a different value). 22) Parameter passing to the stack Is it guranteed that parameters of the function call are passed to the stack in right to left order? See the code: void f(int a,int b) { printf("%d\t%d",a,b);} int main() { int x=3; f(++x,x++); return 0; } In order to know the output of the code,one need to know what is the order of parametr passing to the stack. Is it specified in the ANSI C standard that whenever a function call is made ,parameter are passed from right to left.Or it depends on the stack implementation of the underlying operating system? A) I think it depends upon compiler!! gcc,cc,c++,g++ pushes the arguments of func. from RIGHT to LEFT ..so it shud print :

8
53 try this: printf("%d %d",++x,x++); output: 5 3 i.e same as above (as far as i know)!!! 23) The problem is to print "Hello World" on the screen without using any library function like printf,puts,cout etc.? A) int main( int argc , char ** argv ) { int fd; char * str = "Hello World\n"; if( (fd = open( argv[1] , O_WRONLY ) ) < 0 ) { perror("Open"); return -1; } if( write( fd , str , strlen(str) ) < 0 ) { perror("Write"); return -1; } return 0; } Run as: ./a.out /dev/pts/312 or ./a.out /dev/tty1 This will do on *nix. A) on Linux x86 with gcc you can do this: void main(void) { asm ("int $128" :: "a"(4), "b"(1), "c"("Hello World\n"), "d"(12)); } 24) What's the output? #include <stdio.h> int inc(int i) { return ++i; } int main() { int a,b,c; a = b = c = 0; while( ++a, a=inc(a), a < 3) { while( b=1, c=inc(c), c < 3) ++b, b=inc(b), ++b; } printf("%d %d %d\n", a,b,c); }

9
25) While in a switch Try this out.... int i = k = 2; switch (i) { case 1 : i++; break ; while ( i != 10 ) { case 2 : i++ ; break ; } case 3 : k++ ; break ; } printf ( " %d\t%d\n" , i , k ) ; Is it going to compile??? If no why? If yes? what will be the output? explain How it works??? A) First thing that program gives the compile time error. Because U can't assign one variable to other variable at declaration time. If you declare as int i, k ; i= k = 2; then that program will print 3(i=3) , 3(k=3) . In switch it first evaluate the integer expression and checks for the corresponding case. I think it doesn't matter whatever it is there valid statements. So here matches case 2 . So i is incremented and value now 3. Break will brings the control to out of while statements. So now it will execute whatever statements are there. so k is incremented and value become 3. Now this break will brings control to out of the switch statement. Now the printf will print i and k values as 3 , 3. A) Error Firstly int i=k=2; Needs to be made int k; int i=k=2; By making these changes we will get the error orphaned case for case 2:i++ 26) Life without sizeof Q.If you are not having a sizeof operator in C, how will you get to know the size of an struct? struct point { long x, y; }; A) struct point* p; size = (char*)(p+1) - (char*)p; A) typedef struct a { int a; int b; int c; int d; char array[4]; long long e; } st; main() {

10
st as ; printf("%d \n",(int)(&as+1) - (int)(&as) ); printf("using sizeof syscall = %d\n",sizeof(st)); } 27) wht will be the output of this C program n why #include<stdio.h> int main() { int a,b,c=2,d=4,e=3,f=7; (a,b)=(c,d)+(e,f); printf("%d %d",a,b); return 0; } A) 'a' value is some garbage value, because value to a is neither intialized nor assigned. 'b' value is 11 . (a,b)=(c,d)+(e,f); In this equation left side of equation get the b L value, right side also get the R values of d and f. In that paranthesis it returns the value of last executed. so in that parenthesis it returns b, d and f. A) it works because , is a sequence point which evalutes all of the objects in the list of , in order and evaluates to the last object so a, b = c, d + e, f is b = d + f 28) Complex comments Without actually executing this program, can you guess what the output might be? Assume that your compiler is not C99 compliant, but is C89 compliant. #include <stdio.h> int main (void){ int a = 10, b = 5; int c; c = a//* //*/b ; printf("%d",c); return 0; } A) As for the reference to C89, // was not considered as a comment construct in C89. C99 makes it a valid comment construct. A) in C however the line c = a / /*...*/b; should evaluate as c = a / b; which gives 2 A) Yup, 2 it is!! A C99 compliant compiler would give 10. 29) What is difference between define and typedef in c? A) typedef creates a new name for a type. #define does a textual replacement of data. FOr example, typedef: typedef char* CHAR_POINTER; CHAR_POINTER a, b;

11

Here, both a and b are of type CHAR_POINTER. So, both would be of type char*. #define: #define CHAR_POINTER char* CHAR_POINTER a,b; This is the same as saying char* a,b; Here, a is of type char*, while b is of type char. A) #define is handled by preprocessor and typedef by a compiler. 30) static variable what is the significance of static variable ? and why is it so important in embeded (& system perhaps) programming ? A) static variable is stored in HEAP and not in STACK as all the other local variables will be,therefore it holds its value in between function calls 31) How to resolve scope in C how can I print value of global varible i inside main function. #include <stdio.h> int i = 200; void main() { int i = 100; printf("i = %d\n",i);/* how I can access global i inside main function */ } A) Using Scope Resolution :: Cant we do that using Scope Resolution Operator?? A) There is no scope resolution operator in C. A) Well Guys I got #include <stdio.h> int i = 200; void main() { int i = 100; { extern int i; printf("i = %d\n",i);/* now it print value of global variable i */ } printf("i = %d\n",i);/* now it printvalue of lacal i*/ } A) Another, equally dubious way: #include <stdio.h> int i = 200;

12
int main() { int *pi = &i; int i = 100; printf("i = %d\n",i);/* local i */ printf("i = %d\n", *pi); /*global i*/ } 32) void main() When you are working with Linux, its OK!!! But we know that most programs or assignments discussed here are in context of windows. And like assignment in that thread it was a stand-alone program. So Zaman and Paul...Can you tell me any advantage of using int main() when in a stand-alone program. When you have nothing to do with its return value. It doesn't make any difference. A) When you write code, in any language, you should always be writing it to be as portable as is reasonably possible. You have no way of knowing how or where that code is going to be used in the future. Code is expensive to write and maintain, so we want it to be of good quality and as easy as possible to maintain. In order to do this we need to adopt good software engineering practices, and two of these practices are adhering to language standards and writing portable code (some overlap between these two). So given the choice between writing the standard, portable int main() and the non-standard non-portable void main(), and given that there is virtually no difference in the amont of effort required, why would anyone choose the latter ? The only explnnation I can see is that the person who write void main is either clueless, lazy or just doesn't care about code quality issues. Whatever the reason though, I wouldn't hire them. A) Yes portablity.... But just for the sake of argument, I never rejects any person on these reasons. I have even hired programmers that are not completely familiar with the syntax of C/C++. But that i can teach them. They must have good analytical skills and problem solving skills, and good operating system concepts. I think that's all needed for a good C++ developer. A) Yes, but then you're not hiring a C programmer, you're hiring a trainee, so the criteria would be different. If I'm hiring a C programmer I don't expect to have to teach them very basic stuff about C programing before they become useful. And besides, the sort of person who writes "void main" is probably clueless in many other regards too A) void main(void) - the Wrong Thing Because the standard says so. (To which the answer is usually of the form "but it works for me!") Because the startup routines that call main could be assuming that the return value will be pushed onto the stack. If main() does not do this, then this could lead to stack corruption in the program's exit sequence, and cause it to crash. (To which the answer is usually of the form "but it works for me!") Because you are likely to return a random value to the invokation environment. This is bad, because if someone wants to check whether your program failed, or to call your program from a makefile, then they won't be able to guarantee that a non-zero return code implies failure. (To which the answer is usually of the form "that's their problem"). SOURCE: http://users.aber.ac.uk/auj/voidmain.shtml 33) What is the smallest function in C? A) int x(void) { return 0; }

13
A) Or, if it doesn't need to do anything useful... void x(void) { }

35) Common to C and C++: 1.) What is the value of i in any of the following expressions: i = i++; i++ + ++i etc. Ans - This is undefined behaviour. Undefined does not mean compiler will generate an error. It just means that compiler is free to handle it anyway. So you will see output but you can not rely on it. For more info on it, look at sequence points. Also refer the Standards. 2.) What data type should the function main() return? Ans - According to the C and C++ standards the main() function should return 'int'. And if you are not passing command line arguments, use int main ( void ). 36) The D&E Points of interest 1. Inlining was considered important for the utility of classes. Therefore, the issue was more how to provide it than whether to provide it. The compiler knows best if it has been programmed to inline and it has a notion of time/space optimization that agrees mine(Bjarne's). Furthermore, techniques that require global analysis, such as automatic inlining without user support, tend not to scale well to very large programs. 2. I (Bjarne, from now on please consider it implicit) prefer name equivalence over structural equivalence because I consider it the safest and cleanest model (for linkage). I was therefore pleased to find that this decision didn't get me into compatibility problems with C and didn't complicate the provision of low-level services. This later grew into the 'One-definition rule:' every function, variable, type, constant, etc., in C++ has exactly one definition. 3. Through the acceptance of the C linker came another rule of thumb for the development of C++: C++ is just one language in a system and not a complete system. In other words, C++ accepts the role of a traditional programming language with a fundamental distinction between the language, the operating system, and other important parts of the programmer's world. It makes it essential that a C++ program fragment can call program fragments written in other languages (like C, Fortran) and that a C++ program fragment can itself be called by program fragment written in other languages. 4. Over the years, my experience and that of my colleagues has been that link capability is much more important than source compatibility. 5. When this was introduced into C with Classes (predecessor of C++), the language didn't have references, and C++ borrowed its terminology from Simula rather than from Smalltalk. 6. C with classes introduced the notion of f(void) for a function f that takes no arguments as a contrast to f( ) that in C declares a function that can take any number of arguments of any type without any type check. My users soon convinced me, however, that the f(void) notation wasn't elegant, and that having functions declared f() accept arguments wasn't intuitive. Consequently, the result of the experiment was to have f() mean a function f that takes no arguments, as any novice would expect. It took support from both Doug

14
McIlroy and Dennis Ritchie for me to build up the coverage to make this break from C. Only after they use the word abomination about f(void) did I dare give f() the obvious meaning. However, to this day, C's type rules are much more lax than C++'s, and ANSI C adopted 'the abominable f(void)' from C with Classes. 7. Much later the first of these warnings (in text, "Warning: class X defined as return type of g() did you forget a ';' after '}' ?) was made into an error by banning the definition of new types in return and argument types. class X{ // ... } g (int i, int x, int j) // Warning: class X defined as return type of g() // did you forget a ';' after '}' ? // Warning : j not used { if(i=7) { // Warning: constant assignment in condition // ... } if(x&077==0) { // Warning: == expression as operand for & // ... } } 8. C++ preserves all these advantages and compatibility with C at the cost of abandoning claims to perfection and of some compiler and language complexity. 9. However, only C, Simula, Alogol68, and in one case BCPL left noticeable traces in C++ as released in 1985. Simula gave classes, Algol68 operator overloading, references, and the ability to declare variables anywhere in a block, and BCPL gave // comments. 10. Adding a major feature or concept to a language should not be a leap of faith, but a deliberate action based on experience and fitting into a framework of other features and ideas of how the resulting language can be used. The post-1985 evolution of C++ shows the influence of ideas from Ada (templates, exceptions, namespaces), Clu (exceptions), and ML (exceptions). 11. Allowing implicit int (static a; is valid) is the source of many of the annoying problems with the grammar today. 12. The C++ ANSI/ISO standard committee has decided to deprecate implicit int. That means we may get rid of it in another decade or so. 13. The critical issues in the design of C++ were always those of type, ambiguity, and access control, and not those of syntax. 14. However, the syntax of a language should be designed to follow the semantic notion of the language, not the other way around. This implies that language discussions should focus on what can be expressed rather than how it is expressed. An answer to what often yields an answer to the how, whereas a focus on syntax usually degenerates into an argument over personal taste. 37) far pointer what is far pointer?where we r using it, n for wat purpose? A) Archaic principles for the following memory model. Memory is divided into segments of definite size (say 64KB). If you want to access any part outside of the allowed (current) segment you need to declare your pointer a 'far'. By default, your pointer is 'near', which allows you to access (anything in) the current segment only.

15

All said and done, this is an old concept and unless you are programming at a very lower-level, say making an OS, you should not worry about the near and far pointers. A) it was used in old days. Acctually Far pointer types do not exist for 32 bit compilers.It was a non-standard extension only present in 16 bit C compilers on intel platforms. The only reason people invented the far pointer is because Intel came up with this brain damaged segmented architecture when they designed the 8088 and the far pointer was a hack for C compilers to get around accessing memory in another segment. 32 bit compilers see the memory as a flat memory model with none of this segmented nonsense, so there's no need for them to use the far keyword anymore. And in Flat memory model there is no need for Far Pointer as in flat memory model All calls are NEAR, All addresses are 32 bits, Segment registers never reloaded, Segment overrides never used. But in the segmented memory model there are seperate segments for Ada code, Global Ada data, RTS code, RTS data, Stack, Heaps and Collections and all addresses are 16+32 bits and calls from Ada to RTS uses the far pointer. 38) fflush(); what is d use of fflush(); in c?how n where should we use it? A) fflush is used to flush the stream its declaration is int fflush(FILE *stream);if the given stream has buffered o/p then fflush writes that o/p in associated files .it has no effect on an unbuffered stream . on success it returns 0 else it returns EOF. A) Good answer. Note also that fflush should never be called on an input stream, e.g. fflush(stdin) is invalid and may cause unpredictable behaviour. A) Full info. NAME fflush - flush a stream SYNOPSIS #include <stdio.h> int fflush(FILE *stream); DESCRIPTION If stream points to an output stream or an update stream in which the most recent operation was not input, fflush() causes any unwritten data for that stream to be written to the file, and the st_ctime and st_mtime fields of the underlying file are marked for update. If stream is a null pointer, fflush() performs this flushing action on all streams for which the behaviour is defined above. RETURN VALUE Upon successful completion, fflush() returns 0. Otherwise, it returns EOF and sets errno to indicate the error. 39) What is the difference between getch() and getche() A) GETCH():::This is a function that gets a character from keyboard, does not echo to screen. GETCHE():::This is a function that gets a character from the keyboard, echoes to screen. 40) idiomatic code Well Guys this is an idiomatic code in C while(*str1++==*str2++)

16
; hope u can answer!!! wat does the above code generates ??? note this is not an easy i guess A) It's just a terse old-fashioned way of finding the first non-matching character in two strings. If you substitute = for == then it becomes a terse old-fashioned way of implementing strcpy (I think this may even have been in the first edition of K&R ?). 43) Value (computer science) From Wikipedia, the free encyclopedia In computer science, a value is a sequence of bits that is interpreted according to some data type. It is possible for the same sequence of bits to have different values, depending on the type used to interpret its meaning. For instance, the value could be an integer or floating point value, or a string. Some kinds of value are common to most programming languages (e.g., various kinds of number representations), while others are less commonly supported (e.g., Pascal supports a set type). In C: L-value and r-value Some languages use the idea of l-value and r-value. L-values are values that have addresses, meaning they are variables or dereferenced references to a certain place. R-value is either l-value or non-l-value a term only used to distinguish from l-value. In C, the term l-value originally meant something that could be assigned (coming from left-value, indicating it was on the left side of the = operator), but since 'const' was added to the language, this now is termed a 'modifiable l-value'. An l-value is an expression that designates (refers to) an object. A non-modifiable l-value is addressable, but not assignable. A modifiable l-value allows the designated object to be changed as well as examined. An rvalue is any expression that is not an l-value, it refers to a data value that is stored at some address in memory. 44) what is deference between definition & declaration of external variables? A) extern int i; // declaration (usually in a .h file) int i; // definition (usually in a .c file) 45) can ne-one plz tell me the difference between executable and object file ??? A) Both contain binary code. An executable is complete. All symbols are defined in an executable (except symbols imported from dynamic libraries, but that's another story). An executable is understandable by the underlying operating system. An executable represents a complete ready-to-use compiled application. An object file represents a part of an application. It contains the code of a few functions, but is (usually) incomplete. i.e. it uses functions or external variables which it doesn't define, and so, it must be linked (with a linker) to other object files containing the definitions of these undefined symbols in order to produce an executable file. An object file may have a very specific non-portable format supported by only a few compilers (especially under Windows, but that's quite false on other operating systems). It may not be understood directly by the underlying operating system, though under UNIX systems with ELF object files, executables & object files all this is tightly related and the C linker is almost as related to the OS than the executable dynamic linker. Object files are useful to represent small partially independent parts of a project. Usually, there is a one-toone mapping between a non-header source file and an object file (which contains the compiled binary code).

17
This system allows rebuilding a project with a simple compilation of source files having been modified but not others. Object files are also a mean to distribute language-independent* (but platform-dependent) static libraries, propreitary or not. A static library file is nothing more than a bunch of object files in an archive, optionally containing a header for fast symbol lookup. *language independent means that object files are compiled binary code which can come from assembly, Fortran, C, C++, Ada, Modula, Pascal, etc. source files, and they can gracefully be linked together! 46) linked list cn anybody tell me the practical applications of linked list.. A) There are many applications of linked lists. For example in linux kernel you have process table which is implemented as linked list. The number of processes in the system is dynamic and kernel cannot allocated the memory for these statically. So when ever new process gets spawned , its inserted into the linked list. The queues at network routers, the events in event based simulation ..etc uses linked lists. 47) problem regarding union union a { int i; char ch[2]; }; union a u; u.ch[0]=3; u.ch[1]=2; printf("\n\n\n%d %d %d ",u.ch[0],u.ch[1],u.i); } o/p: 3 2 515 plzz explain how this o/p has come. A) i think u know the definition of union... the output is so because 3 and 2 are botj stored in lower byte and upper byte and in binary together it comes as 0000001000000011 and hence the value of int A) Or to put it another way: 2 * 256 + 3 = 515. You're obviously running this code on a little endian machine with 16 bit ints. 48) please tell me the code for swap two values of pointer without using third temperary variable. A) int main() { int *p1, *p2; int x=10,y=200; p1 = &x; p2 = &y; *p1 ^= *p2 ^= *p1 ^= *p2; return 0; }

18

/* This code uses XOR to swap the values at pointers */ A) You don't need to swap the values, just swap the pointers, e.g. p1 = &x; p2 = &y; // now swap them p1 = &y; p2 = &x; This technique is particularly important when you're swapping something much larger than an int, since it means that you don't need to copy any data. 49) there r 6 tokens... 1)keywords, 2)identifiers 3)constants 4)string literals 5)operators 6)separators 50) thread & process...? wat is the differance between thread & process.....if any...? A) Threads coexist in a single process's memory space, and are therefore much more tightly coupled than processes, which each have their own memory space A) Process: The Process is an instance of a program, a single process can handle different programs or different processes can handle a single program... Thread: A thread is sequence of control with in the process... a thread contains its own stack and all other global variables, file des etc... cna be shared from the process. A PROCESS CAN CONTAIN MULTIPLE NO.OF THREADS.. 51) a++ And ++a confusion Can Sb tell me the ans of the following code using Turbo c:#include<stdio.h> int main() { int a=0,b; b=a++ + ++a + ++a + ++a + ++a + a++; printf("%d %d",a,b); return 0; } A) Even if you know the compiler, the result is still undefined. The same compiler may generate different behaviour in different contexts or with diffferent command line switches (e.g. optimisation level). So the answer stands: the result is undefined, even if you know which compiler is being used. 52) #include<stdio.h> /*this program lists all the prime no. between 2 to 300*/ main() { int a,b; for(a=2;a<=300;a++) {for(b=2;b<=a-1;b++)

19
{if(a%b==0) break;} if(b==a) printf("%d \n",a); }} 53) can any one plz help me !!!! regards comma.. firstly, i would like to know... wheather "," is an operator or separator...? or both.. or none? secondly, can any one tell this program behaviour please...? int main() { int a = 5, b = 10, c, d; c = a, b; d = (a, b); printf("c = %d d = %d", c, d); } c = 5 d = 10 i am confusing with d; howz d is replaced with 10 ???? A) It depends on context - a comma can be a separator or an operator. When it's an operator the LHS is evaluated and discarded and the RHS is evaluated and returned A) Reason: consider the statement c=a,b; since comma operator is having lower priority than assignment operator so it is evaluated as (c=a),b;//first assignment then comma and hence the result is 5 in ur second ststement d=(a,b);/// () is having greater priority than the =(assignment) operator so first (a,b) is evaluated which returns the value of "b" and then this value is assigned to d and hence the result. 54) How to add two numbers without using arithmetic operators ? Here is how you can add two numbers without using any arithmetic operators. The code uses bitwise operators. This code pretty much implements a full adder which adds three bits and returns two bits ( a carry and a sum). A) #include <stdio.h> int add(int a, int b){ if (!a) return b; else return add((a & b) << 1, a ^ b); } int main(){ printf("Enter the two numbers: \n"); int a,b; scanf("%d",&a); scanf("%d",&b);

20
printf("Sum is: %d",add(a,b)); } 55) Can anyone suggest me the best way to find loop in a linked list. Loop here means it can be circular at any node i.e the last node can be pointing to any node. A) Take two pointers to traverse the list. Make first pointer to traverse list step by step and second pointer to traverse the same list two steps at a time (repeat traversing the list with second pointer until the first pointer reaches end of list). At any time if both pointers contain same address saying that there is a loop. If you got any other ways to find loop, pls let me know. 56) Give a one-line C expression to test whether a number is a power of 2. A) n is given number... if n&( n-1) == 0 -------> power of 2 else ---------> not a power of 2 A) Your solution fails for n = 0 (it returns true when it should return false, since 0 is not a power of 2). A better solution: n > 0 && (n & (n - 1)) == 0; 57) an interesting question struct try { char *str; int i; }t; void main(){ //scanf("%s %d",t.str,&t.i); gets(t.str); printf("\n\n\n%s",t.str); } why does the prog give error....null pointer assignment A) Because t.str is a dangling pointer A) A dangling pointer is a pointer that does not point to a valid memory location. Since you didn't allocate any memory for this pointer it's just pointing at some random location. 58) #include<stdio.h> void main() { int x=10,y=10,z=5,i; i=x<y<z; printf("%d",i); } A) the boolean operation (x<y<z) perform left to right it means (10<10<5) gives (0<5) becoz 10<10 is false so it return 0 .again (0<5) return 1 becoz 0<5 so true which is 1.hence output is 1 59) main() { char *str="12345"; printf("%c %c %c ",*str,*(str++),*(str++));

21
} output is 3 2 1 why not 1 2 3? A) The output is undefined or say compiler dependent. I think you have run the above code on Turbo C. Now try running it on gcc and visual C++ as well. 60) small program in c for inputing name and displaying so A) #include <stdio.h> int main(void) { char s[64]; printf("Enter name: "); fgets(s, sizeof(s), stdin); printf("Hello, %s !\n", s); return 0; } VX Works 61) What is a Task? A task is the active element of a VxWorks system. They are the only objects that are scheduled. It is important to separate a task from any code that it may execute during its life. Code is totally passive until executed by a task. As long as it is written correctly (i.e. it follows some simple rules regarding re-entrancy), a piece of code may be executed by more than one task. Tasks can be thought of as running concurrently, though obviously with only a single CPU this is never truly the case. It is a useful way of thinking about them though when designing a system where tasks must share resources, or must synchronise their activities. In both situations each task must make use of synchronisation primitives, such as semaphores or message queues, to ensure that the overall behaviour is correct irrespective of the order in which the tasks really gain CPU time. Comparing VxWorks to other operating systems, a task can be thought of as a thread. The real difference between VxWorks and those other operating systems is that VxWorks has only one process in which all the threads (tasks) run. Looking at VxWorks AE, the same analog of task and thread holds true, but now there is also an analog of the process: the protection domain. Unlike, for example, Unix processes though, the VxWorks AE protection domain is never scheduled. It remains a passive container for tasks, other objects and, of course, memory. 62) What Does Context Switching Entail? Context switching is the mechanism by which a multi-tasking operating system switches control between two threads of execution, thereby giving the illusion of concurrency. Of course, the scheduling algorithm, which is the means of deciding when to switch, and which thread to switch to, will have a dramatic effect on how well that illusion is maintained. A desktop operating system has very different needs to an RTOS in this regard. A RTOS scheduling algorithm, such as the priority pre-emptive one used by VxWorks, is more concerned with predictability (determinism) than a general purpose OS, which is generally more concerned with allocating a fair share of resources to each user/process. For VxWorks, context switching is simply a matter of saving the current state of one task in its TCB, and then restoring the state of the newly selected task. The state in this case is simply the content of the CPU's registers, including the stack pointer and program counter. The context switch time is a function of the number of registers that need to be saved and restored. For this reason, RISC processors, which tend to have many more registers than their CISC counterparts, tend to have longer context switch times. Additionally, extra registers, such as floating point registers also add to this time. It is for that reason that

22
VxWorks tasks can choose whether or not the floating point registers need to be saved. A task that makes no use of floating point arithmetic, does not need to save or restore these registers, and will therefore have a faster context switch time. The VX_FP_TASK option, passed to taskSpawn(), controls whether these registers are saved and restored.

63) Semaphores Basics There are three types of semaphore available in the VxWorks world. Each is optimised for a specific function. This section looks at each of the three types in turn, and explains when to use them and when not to. While there are different create routines for each of the three types, they all share the same interface functions. Binary Semaphores As the name implies, binary semaphores have just two states: full or empty. When full, a call to semTake() will return immediately and a call to semGive() will have no effect (note: semGive() never blocks). When the semaphore is empty, a call to semTake() will block either until the semaphore is given by another task, or the optional timeout expires. Use WAIT_FOREVER for the timeout value to block until the semaphore is available, and NO_WAIT to return immediately, even if the semaphore is not available. When using a timeout, be sure to check the status return, and if it is ERROR check the value of errno to ensure that the reason was a timeout. Binary semaphores are optimised for signalling operations between tasks, or from an ISR to task level. They are the fastest of the three semaphore, and are frequently used within VxWorks ISRs. While they could also be used for mutual exclusion protection, this would be sub-optimal and should be avoided. The mutex semaphore type is designed for ensuring mutual exclusion and has some extra features to protect against misuse. Counting Semaphores Counting semaphores are the logical extension of the binary semaphore. Now, rather than just two states, the semaphore is a counter. As long as the count is greater than zero a call to semTake() will return immediately (decrementing the count first of course). Calls to semGive() increment the count. The timeouts work the same way as in the binary semaphore case. Use a counting semaphore when there are a fixed number of resources to be allocated, e.g. in a driver that wants to limit the number of simultaneous opens, or to count events, e.g. in a producer-consumer type application when the producer can generate multiple blocks of data to be consumed. Mutual Exclusion Semaphores Mutual exclusion semaphores, or mutex semaphores for short, are designed to protect a critical region of code against simultaneous execution by multiple tasks. They are essentially binary semaphores in that they have two states, locked and unlocked, but they also have some additional features designed to further protect against buggy code getting into a critical region. The key differences between mutex semaphores and binary semaphores are as follows:

Recursive Priority inversion protection Delete safety

23
64) Contiguous Memory Allocation Query : When we declare an array, we say that it's elements are contiguous. What memory do we refer to here? The Virtual or Physical?? The main problem is that i want some data to be contiguous in true sense in physical memory?? How can i achieve that? A) Obviously an array must be in contiguous virtual memory. In a VM OS the array will not necessarily be physically contiguous. In a non-VM OS the array will obviously be in contiguous physical memory. 65) Why fflush(stdin) is wrong On occasions you may need to clear unwanted data in an input stream, most commonly keyboard input. One frequently suggested way of doing this is by using fflush(stdin). This is incorrect, and should be avoided, here is why. stdin is a standard FILE* variable that points to the input stream normally used for keyboard input. The fflush() function is deemed to flush buffers. Put the two together and you have a method for clearing the input stream easily, right? WRONG! This is a common misconception in C and C++ programming, an extract from the C standard will help explain: int fflush(FILE *ostream); ostream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

So, if the file stream is for input use, as stdin is, the behaviour is undefined, therefore it is not acceptable to use fflush() for clearing keyboard input. 66) Merge sort In computer science, merge sort or mergesort is a O(n log n) sorting algorithm. It is easy to implement merge sort such that it is stable, meaning it preserves the input order of equal elements in the sorted output. It is an example of the divide and conquer algorithmic paradigm. It is a comparison sort. The algorithm was invented by John von Neumann in 1945. Conceptually, merge sort works as follows: Divide the unsorted list into two sublists of about half the size Sort each of the two sublists recursively until we have list sizes of length 1, in which case the list itself is returned Merge the two sorted sublists back into one sorted list. Mergesort incorporates two main ideas to improve its runtime: A small list will take fewer steps to sort than a large list.

24
Fewer steps are required to construct a sorted list from two sorted lists than two unsorted lists. For example, you only have to traverse each list once if they're already sorted (see the merge function below for an example implementation In sorting n items, merge sort has an average and worst-case performance of O(n log n). If the running time of merge sort for a list of length n is T(n), then the recurrence T(n) = 2T(n/2) + n follows from the definition of the algorithm (apply the algorithm to two lists of half the size of the original list, and add the n steps taken to merge the resulting two lists). The closed form follows from the master theorem. 66) EOF is an integer defined in <stdio.h> so wht is the integral value of EOF? A) How are you signalling end of file to to your program ? E.g. under Linux/Unix/Mac OS X etc it would be control-D. I think under DOS/Windows/etc it's probably something non-standard like control-Z (?). A) That's only a terminal-specific thing that has nothing to do with the input programs are getting! Under Linux/Unix/Mac OS X, I'm pretty sure it terminal I/O can be very much controlled with stty. From a program point of view, input from a file, fifo, socket, pipe or terminal, comes as a raw stream of chars, and read() fails when the end is reached. Note that you can very well send an EOT (ASCII character 04) character as input to a program with CTRL+V CTRL+D or whatever terminal-specific key stroke sequence. The EOF macro expands to an implementation-dependent constant expression whose value is a negative int. This valus is often -1, but it may be -2, -16578 or any other negative value. A) When you enter -1, it puts two characters in the stream : '-' and '1' whose ASCII (I don't know for EBCDIC) values are 45 (decimal) and 49 (decimal) respectively. Then, when these characters are read, c is set to these integer values. Typically char values are in range [-128,127] or [0,255] and are returned as a positive int (so, if char has range [-128,+127], 256 is added to the char value) by fgetc(), getchar() and other file stream functions. So, you see that a negative value can't be returned for a normal character. A negative value can only be returned for signaling the end of file or a hardware* error. * I mean: any non-EOF error, such as a socket connection lost, ulimit reached, or other reasons. 67) What's the value of i++ + i++? It's undefined. Basically, in C and C++, if you read a variable twice in an expression where you also write it, the result is undefined. Don't do that. Another example is: v[i] = i++; Related example: f(v[i],i++); Here, the result is undefined because the order of evaluation of function arguments are undefined. Having the order of evaluation undefined is claimed to yield better performing code. Compilers could warn about such examples, which are typically subtle bugs (or potential subtle bugs). I'm disappointed that after decades, most compilers still don't warn, leaving that job to specialized, separate, and underused tools 68) optimization When talking about computer programming, optimization refers to improving a program. This is actually a misnomer, because generating an optimal solution is far too complex a problem. Instead, we have to settle

25
for a solution that is better than the old one. In terms of code generation, better means code that executes faster, although there are cases where code that occupies less space is more valuable (e.g. embedded platforms with limited memory available). Optimization occurs at two levels. The programmer can manually optimize a program or a compiler program can automatically optimize it. As Knuth, Kernighan, and Pike suggest above, though, manual optimization is best left until a performance problem occurs; after all there is no sense in spending days making your program run seconds faster if nobody is waiting for it. Making the code go faster also has a tendency to make it more complicated, too, so premature optimization is likely to leave you with more buggy and less maintainable code. 69) sequence point In the C language, a sequence point is a place in code just after the termination of an expression, before any of the ||, &&, ?:, or , operators, or just before a function call, after all of its arguments have been evaluated. At a sequence point, all variable updates and side-effects since the previous sequence point are guaranteed to have taken place. From the ISO Standard: Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The first sentence is pretty obvious: you're not allowed to modify a variable twice between sequence points. (So a statement like i = 5 * i++; is not allowed, because i is both being assigned to, and updated as a side effect of the ++.) The second sentence is slightly less obvious, and best explained with an example. The behavior of this code: a[i] = i++; is undefined. Why? because the 'prior value' of i is being accessed to determine where in a[], instead of just to compute the value of i++. 70) XOR swap A) how can you swap two variables without a temporary variable? simple! the almost-magical XOR operator! in C/C++, you can do this: a^=b^=a^=b; (addendum, 2001-08-22) ... Well, actually you can not, in fact, do that. Or you can, it's just not 100% guaranteed to work according to the ISO C standard. To use the xor swap correctly, you need something more like this: a^=b; b^=a; a^=b; Why? Well, in ISO C, a variable is not allowed to be modified more than once between sequence points. Since a is modified twice in the original expression, the expression is undefined, and thus might not work on all compilers. First off, if it was to be parenthesized, it would go: a ^= (b ^= (a ^= b)); 3 2 1

26
This just helps visualize the order that things happen in. Lets take a = 1001 1011 b = 1100 0110 The first XOR modifies a: a = 1001 1011 b = 1100 0110 a' = 0101 1101 The second XOR then takes a' and b, storing the result into b': b = 1100 0110 a' = 0101 1101 b' = 1001 1011 Note that b' now is the same value as the original a. The last XOR then operates on a' and b', storing into a": a' = 0101 1101 b' = 1001 1011 a" = 1100 0110 The final results stored (a" and b') are the same as the original a and b, except swapped. 71) virtual memory A) Virtual memory is used to provide the illusion of either having more memory than you really do (by multiplexing multiple virtual addresses onto a smaller set of physical addresses) or having more processors than you really do (by time-slicing the processor and providing each time-sliced process with a separate address space). The address space available to a process running in a system with a memory management unit (MMU). The virtual address space is divided into pages. Each physical address output by the CPU is split into a virtual page number (the most significant bits) and an offset within the page (the n least significant bits). Each page thus contains 2n bytes (or whatever the unit of addressing is). The offset is left unchanged and the virtual page number which is mapped by the MMU to a physical page number. This is recombined with the offset to give a physical address - a location in physical memory (RAM). Virtual memory is usually much larger than physical memory. Paging allows the excess to be stored on hard disk and copied to RAM as required. This makes it possible to run programs for which the total code plus data size is greater than the amount of available RAM. This is known as "demand paged virtual memory". A page is copied from disk to RAM when an attempt is made to access it and it is not already present. This paging is performed automatically by collaboration between the CPU, the MMU and the operating system kernel, and the program is unaware of it. The performance of a program will depend dramatically on how its memory access pattern interacts with the paging scheme. If accesses exhibit a lot of locality of reference, i.e. each access tends to be close to previous accesses, the performance will be better than if accesses are randomly distributed over the program's address space thus requiring more paging. In a multitasking system, physical memory may contain pages belonging to several programs. Without demand paging, an OS would need to allocate physical memory for the whole of every active program and its data. Such a system might still use an MMU so that each program could be located at the same virtual address and not require runtime relocation. Thus, virtual addressing does not necessarily imply the existence of virtual memory. Similarly, a multitasking system might load the whole program and its data into physical memory when it is to be executed and copy it all out to disk when its timeslice expires. Such swapping does not imply virtual memory and is less efficient than paging. Some application programs implement virtual memory wholly in software, by translating every virtual memory access into a file access, but efficient virtual memory requires hardware and operating system support.

27
72) "Segmentation fault" is the error message that most POSIX-driven systems (for example, Linux or Unix) will emit when any program attempts to access memory in an invalid manner. This occurs most frequently by attempting to use memory not allocated to the program, although simply running out of memory will, on some systems, produce the same error message. The signal that a program receives, and usually returns as a crash code, is "SIGSEGV". Although "Segmentation fault" may not seem to be a particularly useful error message, an experienced programmer who has worked with his or her programming language of choice for a sufficient period of time is likely to inform you that "Segmentation fault" is, indeed, a nearly useless error message. It is nearly useless because it can occur for a wide variety of potentially non-obvious reasons. Although "Segmentation fault" always implies a memory error of some form, the number of ways that such an error could occur is far larger than it might first appear. Almost any error that compiles anyway will result in a segmentation fault. 73) Bus error A) In unix, a bus error results in your process receiving a SIGBUS signal. Bus errors are typically caused by attempts to access bad memory or attempts to access data that is not word aligned on architectures that require multibyte data to be word aligned. Examples of "bad" memory might include areas that are reserved and therefore could never be valid, or areas of device mapped memory that is either nonexistant or currently in an error state. 74) Q:Why does Some OS require Ctrl+Alt+Del to begin Que:Some Operating Systems including Microsoft Server 2003 require u to press Ctrl+Alt+Del before password entry.What's so speacial about this key sequence?How does it helps to keep security? A) Only Windows can respond to it In Windows, a Ctrl-Alt-Del notification can be received by Windows Logon process only. Neither can these keys be redefined for some other purpose nor can any user/malicious program receive the notification of this event. Whe we log in by pressing Ctrl-Alt-Del, we can be sure that it is the operating system, rather than a third party program or some malicious program, that is responding to the key combination and bringing up the log in screen and that it is therefore safe to enter a password. A) Absolutely correct,infact it is the only key sequence which can't be trapped in user mode.This key sequence can only be trapped in kernel mode. So, we know that only OS will know whether this key sequence has been pressed 75) What is canonicalization? A) Canonicalization issues can be used by attacker to bypass security checks by knowing that when a program handles some other program's data, it doesn't do the same security check. The way all of us would probably have heard about Canonicalization is the (in)famous .. dot dot vulnerability of IIS,which causes attacker to get any file on the server using a crafter URL. %systemroot%\inetpub\wwwroot is the only directory which the IIS allows u to access but a %systemroot%\inetpub\wwwroot\cgi-bin\..\..\..\windows\my.pwl causes files on u'r computer to be accessed (remember .. is previous directory) because the server trusts path beginning with this %systemroot%\inetpub\wwwroot A) Canonicalization is the process that determines how various equivalent forms of a name are resolved to a single standard name. This standard name is also called as "Canonical" name. e.g. The file names c:\paritosh\pari.txt, pari.txt and ..\..\pari.txt refer to the same file on a my computer. Canonicalization is the process which maps all such names to c:\paritosh\pari.txt.

28
76) What should a professional software designer consider in the design and implementation of code? (Solution: The following are some of the considerations: Throughput Latency Reliability Usability Resource limitations Supportability) 77) Explain these particular species of wabbit Each one of these particular species of wabbit were written using a form or "Programming language", Which are they? 1(First)-> (main() {for(;;)fork();}) 2(Second)-> ($0 & $0 &) A) Explanation main() { for(;;) fork(); } This one is a C program. fork() function works in Unix/Linux. The declaration of the function is present in unistd.h. It creates an image of the same process and then both the processes run parallely. Look up the man pages to find out more on fork() or ask here. So, this program replicates itself infinitely, since the fork() is inside an infinte loop. Now these replicas of the process further replicates thereby depleting the resources, memory and most importantly process table. The process table gets filled up by these processes. Hence no new process can run. This also means that you can't kill this fork-bomb, because to kill the fork bomb you need to start a new process called "kill". The only method left is to do a hard-reboot. $0 & $0 & A shell script. $0 represents the name of the script itself. So this one, calls itself recursively (twice in each iteration) as background processes. Consequence is same. The process table runs out of space. So you have to do hard reboot. However, the fork bomb by the C code can be detected by Linux kernel because it has fork-bomb detection algorithm built into it. The Linux kernel initiates a recovery process within one minute and kills the forking processes. However I have found that the recovery process is not a very stable one since the console (:0) where the root logs in becomes unusable. The fork bomb by the shell script goes undetected, perhaps because the process replication in this case is handled by the shell and not the kernel. (The fork-bomb-detection algorithm is built into the kernel. Remember?) The last two paragraphs I have written is from my personal experience and experiments. If anyone finds anything wrong, please correct me by posting here. Or if anyone has a different experience with his/her Linux box, please share it with us by posting here. 78) WITHOUT MAIN write a program in c without using main(). Is it possible , if yes ,how? A) Writing a conforming C or C++ program without main() function is possible. Simply, use a C or C++ implementation supporting an extension providing such a mean. For example, MinGW 3.4.5 for Win32 supports WinMain as an extension.

29
Any (console or GUI) application having a WinMain, but no main, function, is valid with MinGW 3.4.5. It compiles and run fine. There are also a lot of compilers that let you write a startup assembly module... You can change this startup module in order to call another function, such as NotMain(). Finally, linkers may provide a mean to change the entry point... Replacing _start, START or whatever entry point used by default, by the startup code of the runtime library, with a user provided entry point. Providing a function name, may or may not work, depending on the compiler, and whether some necessary startup code has to be executed before any user defined function. An interesting thing, which may work with some compilers, is to set the entry point, through a linker option, to _abort or ExitProcess... That may be funny. :) 79) difference betwee SOURCE CODE and OBJECT CODE? A) Source code is the readable text (mostly) that compiler consumes to output processed object code. Object code is used by the linker and generates the executable. 80) Tell me how???? Tell me d o/p nd why is that so???? main() { int i=10; if(-1 < sizeof(++i)) printf("Wipro" ); else printf("Sasken" ); } A) Sizeof is the compile time unary operator. So it'll not evaluate the _expression. So ++i will not be evaluated. So the value of i is 10. Next, Sizeof operator yeilds unsigned integer value. You are comparing signed value and unsigned value. (ie) -1(Signed value) and 4(unsigned value) If you are comparing signed int value and unsigned int value then signed value will be converted to unsigned value. (Refer K & R 2, page no: 44 & page no: 198 (Arithmatic Conversions) ) So if you are taking -1 as a unsigned value then it'll become a biggest positive no. So the condition fails, and it'll print sasken. 81) What is the difference between the declaration and the definition of a variable? The definition is the one that actually allocates space, and provides an initialization value, if any. There can be many declarations, but there must be exactly one definition. A definition tells the compiler to set aside storage for the variable. A declaration makes the variable known to parts of the program that may wish to use it. A variable might be defined and declared in the same statement. 82) Whats short-circuiting in C expressions? What this means is that the right hand side of the expression is not evaluated if the left hand side determines the outcome. That is if the left hand side is true for || or false for &&, the right hand side is not evaluated. 83) Whats wrong with the expression a[i]=i++; ? Whats a sequence point? Although its surprising that an expression like i=i+1; is completely valid, something like a[i]=i++; is not. This is because all accesses to an element must be to change the value of that variable. In the statement a[i]=i+

30
+; , the access to i is not for itself, but for a[i] and so its invalid. On similar lines, i=i++; or i=++i; are invalid. If you want to increment the value of i, use i=i+1; or i+=1; or i++; or ++i; and not some combination. A sequence point is a state in time (just after the evaluation of a full expression, or at the ||, &&, ?:, or comma operators, or just before a call to a function) at which there are no side effects. The ANSI/ISO C Standard states that Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. At each sequence point, the side effects of all previous expressions will be completed. This is why you cannot rely on expressions such as a[i] = i++;, because there is no sequence point specified for the assignment, increment or index operators, you don't know when the effect of the increment on i occurs. The sequence points laid down in the Standard are the following: * The point of calling a function, after evaluating its arguments. * The end of the first operand of the && operator. * The end of the first operand of the || operator. * The end of the first operand of the ?: conditional operator. * The end of the each operand of the comma operator. * Completing the evaluation of a full expression. They are the following: o Evaluating the initializer of an auto object. o The expression in an ?ordinary? statement?an expression followed by semicolon. o The controlling expressions in do, while, if, switch or for statements. o The other two expressions in a for statement. o The expression in a return statement. 84) Is 5[array] the same as array[5]? Yes! Since array subscripting is commutative in C. That is array[n] == *((array)+(n)) == *((n)+(array)) == n[array] 85) Is memory allocated when a var is declared? A) No memory is not allocated when a variable is declared. Memory is allocated only when a variable is defined. int a=0; //definition. mem allocated. int b; //defintion. mem allocated int c(5); //definition. mem allocated extern int d; //declaration. no mem allocated A) Storage for variables is allocated at some place before first use of the variable. It may be after declaration, and before first use. It may be at the start of the enclosing compound-statement. It may be at the start of the function. It may be at startup time (even for automatic and register variables). It may be before you've designed your program! Yes, it's physically possible!

31
86) What is a const pointer? Answer: The access modifier keyword const is a promise the programmer makes to the compiler that the value of a variable will not be changed after it is initialized. The compiler will enforce that promise as best it can by not enabling the programmer to write code which modifies a variable that has been declared const. A const pointer, or more correctly, a pointer to const, is a pointer which points to data that is const (constant, or unchanging). A pointer to const is declared by putting the word const at the beginning of the pointer declaration. This declares a pointer which points to data that cant be modified. The pointer itself can be modified. The following example illustrates some legal and illegal uses of a const pointer: const char *str = hello; char c = *str /* legal */ str++; /* legal */ *str = a; /* illegal */ str[1] = b; /* illegal */ The first two statements here are legal because they do not modify the data that str points to. The next two statements are illegal because they modify the data pointed to by str. Pointers to const are most often used in declaring function parameters. For instance, a function that counted the number of characters in a string would not need to change the contents of the string, and it might be written this way: my_strlen(const char *str) { ....int count = 0; ....while (*str++) ....{ .........count++; ....} ....return count; } Note that non-const pointers are implicitly converted to const pointers when needed, but const pointers are not converted to non-const pointers. This means that my_strlen() could be called with either a const or a non-const character pointer. 87) how typecating works in C/C++ how writing int i=10; (float)i; converts it to float temporarily.....how that converson is performed??? A) This is a common source of confusion for beginners. In C there are two quite different categories of typecasts, whch unfortunately have the same syntax, e.g. int i; unsigned int j = (unsigned int)i; // typecast with no conversion of the underlying data char c = (char)i; // typecast with conversion of the underlying data (width of data has changed) float x = (float)i; // typecast with conversion of the underlying data (format of data has changed) 88) inplicit int A) Either you're programming in modern C: C99. In that case, implicit int has been banned (and any program using implicit int feature is ill-formed, a diagnostic message is required, and behavior is undefined if the compiler outputs a program). But, in C99, you don't have to return explicitly any value from main(), 0 is returned. From n1124 (= C99 + TC1 + TC2)

32

If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;10) reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified. If you're using the old, but widely used, C90, then, implicit int is permitted. Any C program for which the standard ISO/IEC 9899:1999 says that it has undefined behavior, has undefined behavior. Undefined behavior means nothing more than "the standard doesn't impose anything on the behavior of this program". If the compiler doesn't document any specific behavior, then, the compiler is free to do anything it wants when this program is executed, and yet claim to be conforming to the C standard. If the compiler does document (you can't claim that it does document something without having RTFM) a specific behavior, then, you can rely on it, but your program will not be portable to other compilers. 89) diff b/w union n structure A) In unions, there's only one field stored at a time. In structures, all fields can be stored at the same time. In other words, a structure is a record, containing several values, while unions can only store a single value. For example: struct {int x; float y;} s; s.x=42; s.y=40.5; printf("%d %g", s.x, s.y); /* should display 42 40.5 */ union {int x; float y;} s; s.x=42; /* ok, but now, you mustn't read s.y */ s.y=40.5; /* ok, but now, you mustn't read s.x. s.x is definitively lost */ printf("%g", s.y); /* should display 40.5 */ 90) C99 Note: C99 is also the name of a C compiler for the Texas Instruments TI-99/4A home computer. Aside from being a C compiler, it is otherwise unrelated. After the ANSI standardization process, the C language specification remained relatively static for some time, whereas C++ continued to evolve, largely during its own standardization effort. Normative Amendment 1 created a new standard for the C language in 1995, but only to correct some details of the C89 standard and to add more extensive support for international character sets. However, the standard underwent further revision in the late 1990s, leading to the publication of ISO 9899:1999 in 1999. This standard is commonly referred to as "C99." It was adopted as an ANSI standard in March 2000. C99 introduced several new features, many of which had already been implemented as extensions in several compilers: Inline functions Variables can be declared anywhere (as in C++), rather than only after another declaration or the start of a compound statement Several new data types, including long long int, optional extended integer types, an explicit boolean data type, and a complex type to represent complex numbers Variable-length arrays Support for one-line comments beginning with //, as in BCPL or C++ New library functions, such as snprintf New header files, such as stdbool.h and inttypes.h

33
Type-generic math functions (tgmath.h) Improved support for IEEE floating point Designated initializers Compound literals Support for variadic macros (macros of variable arity) restrict qualification to allow more aggressive code optimization C99 is for the most part upward-compatible with C90, but is stricter in some ways; in particular, a declaration that lacks a type specifier no longer has int implicitly assumed. The C standards committee decided that it was of more value for compilers to diagnose inadvertent omission of the type specifier than to silently process legacy code that relied on implicit int. In practice, compilers are likely to diagnose the omission but also assume int and continue translating the program. GCC and other C compilers now support many of the new features of C99. However, there has been less support from vendors such as Microsoft and Borland that have mainly focused on C++, since C++ provides similar functionality improvement. GCC, despite its extensive C99 support, is still not a completely compliant implementation; several key features are missing or don't work correctly. 91) Usage C's primary use is for "system programming", including implementing operating systems and embedded system applications, due to a combination of desirable characteristics such as code portability and efficiency, ability to access specific hardware addresses, ability to "pun" types to match externally imposed data access requirements, and low runtime demand on system resources. C has also been widely used to implement end-user applications, although as applications became larger much of that development shifted to other, higher-level languages. One consequence of C's wide acceptance and efficiency is that the compilers, libraries, and interpreters of other higher-level languages are often implemented in C. C is used as an intermediate language by some higher-level languages. This is implemented in one of two ways, as languages which: Emit C source code, and one or more other representations: machine code, object code, and/or bytecodes. Examples: some Lisp dialects (Lush), Squeak's C-subset Slang. Emit C source code only, and no other representation. Examples: Eiffel, Sather; Esterel. C source code is then input to a C compiler, which then outputs finished machine or object code. This is done to gain portability (C compilers exist for nearly all platforms) and to avoid having to develop machinespecific code generators. Unfortunately, C was designed as a programming language, not as a compiler target language, and is thus less than ideal for use as an intermediate language. This has led to development of C-based intermediate languages such as C--. 92) C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. It has since spread to many other platforms, and is now one of the most widely used programming languages. C has also greatly influenced many other popular languages, especially C++, which was originally designed as an enhancement to C. It is the most commonly used programming language for writing system software, though it is also widely used for writing applications. 93)Constructs valid in C but not C++ One commonly encountered difference is that C allows a void* pointer to be assigned to any pointer type without a cast, whereas C++ does not; this idiom appears often in C code using malloc memory allocation. For example, the following is valid in C but not C++:

34
void* ptr; int *i = ptr; or similarly: int *j = malloc(sizeof(int) * 5); /* Implicit conversion from void* to int* */ In order to make the code compile in both C and C++, one must use an explicit cast: void* ptr; int *i = (int *) ptr; int *j = (int *) malloc(sizeof(int) * 5); Another portability issue from C to C++ are the numerous additional keywords that C++ introduced. This makes C code that uses them as identifiers invalid in C++. For example: struct template { int new; struct template* class; }; is legal C code, but is rejected by a C++ compiler, since the keywords "template", "new" and "class" are reserved. There are many other C syntaxes which are invalid or behave differently in C++ : The comma operator can result in an "l-value" (a quantity that can be used for the left-hand side of an assignment) in C++, but not in C. C does not allow a given typedef to be duplicated in the same scope, whereas C++ allows redundant typedefs. Enumeration constants (enum values) are always of type int in C, whereas they are distinct types in C++ and may have size different from int. C++ identifiers are not allowed to contain two or more consecutive underscores, whereas C identifiers may. C++ also changes some C standard-library functions to add additional const qualifiers, e.g. strchr returns char* in C and const char* in C++. In both C and C++ one can define nested struct types, but the scope is interpreted differently (in C++, a nested struct is defined only within the scope/namespace of the outer struct). Non-prototype ("K&R"-style) function declarations are not allowed in C++, although they have also been deprecated in C since 1990. Similarly, implicit function declarations (using functions that have not been declared) are not allowed in C++, but have also been deprecated in C since 1999. C allows struct, union, and enum types to be declared in function prototypes, whereas C++ does not. A struct, union, or enum declaration in C++ declares an implicit typedef, while in C it does not. In order to intermix C and C++ code, any C++ functions which are to be called from C-compiled code must be declared as extern "C". 94) Cross compiler A cross compiler is a compiler capable of creating executable code for a platform other than the one on which the cross compiler is run. Such a tool is handy when one wants to compile code for a platform that you don't have access to, or because it is inconvenient or impossible to compile on that platform (as is the case with embedded systems, on which various kinds of microcontrollers run with a minimal amount of memory for their own purpose). Cross-compilation is typically more involved and prone to errors than with native compilation. Due to this, cross-compiling is normally only utilized if the target is not yet self-hosting (i.e. able to compile programs on

/* Implicit conversion from void* to int* */

35
its own), unstable, or the build system is simply much faster. For many embedded systems, crosscompilation is simply the only possible way to build programs as the target hardware does not have the resources or capabilities to compile code on its own. Uses of cross compilers The fundamental use of a cross compiler is to separate the build environment from the target environment. This is useful in a number of situations: Embedded computers where a device has extremely limited resources. For example, a microwave oven will have an extremely small computer to read its touchpad and door sensor, provide output to a digital display and speaker, and to control the machinery for cooking food. This computer will not be powerful enough to run a compiler, a file system, or a development environment. Compiling for multiple machines. For example, a company may wish to support several different versions of an operating system or to support several different operating systems. By using a cross compiler, a single build environment can be maintained that would build for each of these targets. Compiling on a server farm. Similar to compiling for multiple machines, a complicated build that involves many compile operations can be executed across any machine that is free regardless of its brand or current version of an operating system. Bootstrapping to a new platform. When developing software for a new platform, or the emulator of a future platform, one uses a cross compiler to compile necessary tools such as the operating system and a native compiler. Use of virtual machines (such as Java's JVM) ameliorate some of the problems for which cross compilers were developed. The virtual machine method allows the same compiler output to be used by both the host and the target system. Typically the hardware architecture differs (e.g. compiling a program destined for the MIPS architecture on an x86 computer) but cross-compilation is also applicable when only the operating system environment differs, as when compiling a FreeBSD program under Linux, or even just the system library, as when compiling programs with uClibc on a glibc host. 95) What is a pointer? A pointer is a special variable that is used for storing some memory address. So sizeof(pointer) is small and depends on operation system. For Win32 it equals 4 bytes. A pointer has a type "Pointer to some type". A pointer can be converted to integer value and integer value can be converted to a pointer. It is used widely in the Windows API functions. 96) malloc/calloc both allocate memory, calloc has slightly different syntax . Most importantly: calloc() zeros out allocated memory, malloc() doesn't. calloc() a tiny bit slower Dynamic memory allocation #include <stdlib.h> int *foo(int n) { int i[10]; /* memory allocated here */ int i2[n]; /* ERROR: NOT VALID! */

36
int *j; j = (int *)malloc(n * sizeof(int)); /* Alternatively: */ /* j = (int *)calloc(n, sizeof(int)); */ return j; } /* is memory deallocated here; js not */ void bar() { int *arr = foo(10); arr[0] = 10; arr[1] = 20; /* ... do something with arr ... */ free(arr); /* deallocate memory */ } Not calling free() leads to memory leaks ! 97) The stack and the heap A) Local variables, function arguments, return value are stored on a stack . Each function call generates a new "stack frame". After function returns, stack frame disappears along with all local variables and function arguments for that invocation. 98) Memory leaks A) Memory leaks are one of the worst kinds of bugs. often, no harm done at all, eventually may cause longrunning program to crash out of memory,very hard to track down Special tools (e.g. valgrind) exist to debug memory leaks 99) Use of volatile A) A variable should be declared volatile whenever its value can be changed by something beyond the control of the program in which it appears, such as a concurrently executing thread. Volatile, can appear only once in a declaration with any type specifier; however, they cannot appear after the first comma in a multiple item declaration. For example, the following declarations are legal /* Let T denotes some data type */ typedef volatile T i; volatile T i; T volatile i ;

37
And the following declaration is illegal T i, volatile vi ; Volatile qualifiers can be used to change the behavior of a type. For example, volatile int p = 3; declares and initializes an object with type volatile int whose value will be always read from memory. Use of volatile - An object that is a memory-mapped I/O port - An object variable that is shared between multiple concurrent processes - An object that is modified by an interrupt service routine - An automatic object declared in a function that calls setjmp and whose value is-changed between the call to setjmp and a corresponding call to longjmp 100) How to read integers from standard input? I wanna read integers from standard input e.g. Keyboard .. Integers can be upgraded to long also so But i dont wanna use scanf function ... is there any other function or macro? I used getch ... but its truncating integer value to fit in character value .... A)Use scanf, or fgets + sscanf, or fgets + atol. suggest that you don't use scanf for single char input. scanf is also considered to be a security hole. But that doesn't mean that you shouldn't use it, where appropriate. But, scanf is not too bad for streamed input. For line-based input, scanf is usually inappropriate, especially because it's mis-understood. But, line-based input is often evil, and sometimes, guys who use it, are doing so only because their default terminal settings with the default terminal of their system are configured so that the console input looks like a line based thing. Doing line-based input where it's a natural interface (for the user and for other programs) is ok. Doing line-based input everywhere is a good mean to make any advanced user, hate your program interface.

38

A) Useful websites http://www.research.att.com/~bs/bs_faq.html (Stroutstrup blog) http://www.research.att.com/~bs/bs_faq2.html#overload-dot http://www.more-c.blogspot.com/ http://guideme.itgo.com/atozofc/ http://guideme.itgo.com/atozofc/#revisionhistory http://www.everything2.com/index.pl?node_id=855828&lastnode_id=0 http://www.eskimo.com/~scs/cclass/krnotes/top.html http://www.thecareerplus.com/?page=resources&cat=10 http://www.opengroup.org/onlinepubs/009695399/xrat/xsh_chap02.html#tag_03_02_08_03 http://tech-tuts.blogspot.com/2006/08/c_05.html http://tech-tuts.blogspot.com/2006/08/c.html http://www.kuro5hin.org/?op=displaystory;sid=2001/2/23/194544/139 http://www.mycplus.com/forum/forum_posts.asp?TID=12&PN=1 http://www.jobsdream.com/info/tips/resumeprep233.htm http://www.open-std.org/jtc1/sc22/wg21/ (for C++) http://www.technoplaza.net/programming/lesson9.php http://www.codeproject.com/tips/lovelypointers.asp http://cprogrammers.blogspot.com/ http://home.att.net/~jackklein/c/c_main.html http://users.aber.ac.uk/auj/voidmain.shtml http://www-128.ibm.com/developerworks/linux/library/l-memory/

You might also like