Monday, August 31, 2009

C Interview Questions - 100

Hi,
This is a compilation of selective & tricky 'C' questions from internet/FAQs/Dumps so that it could be beneficial for everyone during various scenarios like interviews/exams/quiz.

1. In order to assign attributes to the pointer itself, rather than to the pointed-to object, you put the attributes after the asterisk. like ' char *const p = &c; ' - True/False
Answer - True. It is a const pointer to a char.

2. What is the output of the below code ?
char **p ="Hello";
printf("%s",**p);
return 0;
Answer - Error message 'cannot convert from 'char [6]' to 'char ** ' '

3. There is a char * pointer that points to some ints, and what should be done to step over it ?
Answer -
Consider p is the char * pointer.
int *ip = (int *)p;
p = (char *)(ip + 1);

4. What changes has to be done to get the ouput as "9 8 7 6 5" by the same recursive call
method ?
int main(void) {
int i=9;
printf("%d \t",i--);
if(i)
main();
return 0;
}
Answer - Define 'int i =9' as 'static int i =9'

5. What is the output in the below program ?
void main() {
int z = 12;
printf("%d",printf("Mr.123\\"));
printf(”%d”,printf(”%d%d%d”,z,z,z));
}
Answer - Mr.123\7
1212126
The printf() returns the number of characters sent to the standard output device.

6. You can't 'shift' an array - True/False
Answer - False

7. Is it possible to do like this in C ?
char s[8];
s="ABCD1234";
Answer - No. It is not possible.

8. bit-fields do not provide a way to select bits by index value - True/False
Answer - True

9. Does 'char *a' allocate some memory for the pointer to point to ?
Answer - No. It allocates space only for the address and not for the info that it is pointing to.

10. A null pointer is does not to point to any object or function - True/False
An uninitialized pointer might point anywhere - True/False
Answer - True, True

11. The address of operator will never yield a null pointer - True/False
malloc returns a null pointer when it fails - True/False
Answer - True, True

12. char y[] is not identical to char *y - True / False . Explain the reason for either true/false.
Answer - True.

13. What would be output of the below code ?
char x[] = "abcde";
char *y= "abcde";
printf("%c \n", x[3]);
printf("%c \n", y[3]);
Answer - Both will give the same output.
The array declaration char x[] requests that space for six characters be set aside in the name 'x'
The pointer declaration requests a place that holds a pointer to be known by name 'y'

when the compiler sees the expression x[3], it emits code to start at the location ``x'', move three past it, and fetch the character there.
When it sees the expression y[3], it emits code to start at the location ``y'', fetch the pointer value there, add three to the pointer, and finally fetch the character pointed to.

14. Is it possible to have char x[5] in one file a declaration extern char * in other file ?
Answer - No . It is not possible. In one source file you defined an array of characters and in the other you declared a pointer to characters. C does not allow this.

15. What is dangling pointer ?
Answer - The pointer that does not point to a valid object. 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. That is, sometimes if a pointer is freed but not assigned NULL or 0, it becomes dangling as it might still point to the memory location of freed memory even though it does not have the data. And if the program tries to derefernce it , unpredictable behavior may result.

16. Why does the below code cause segmentation fault ?
int* z = NULL;
*z = 1;
Answer - The pointer z is initialized to NULL and hence It points to memory address 0x00. Dereferencing it will give a segmentation fault.

17. What are the two problems in the below code ?
char *s1 = "Hello, ";
char *s2 = "world!";
char *s3 = strcat(s1, s2);
Answer - s1 is in read-only memory which therefore cannot necessarily be modified. If s1 is declared as an array, it should have the size to accomodate s2 also.

18. What is the problem with the below code ?
i) char a[] = "Hello";
char *p = "Hello";
My program crashes if I try to assign a new value to p[i].
Answer - p is in read-only memory which therefore cannot necessarily be modified.

ii) char *a = "abcdef";
*a = 'X';
Answer - Same as above.

19. Some compilers have a switch to control if string literals are writable or not - True/False
Answer - True

20. Three attributes can be assign to a pointer: const / volatile / restrict - True/False
Answer - True. Yes, these are attributes.

21. What are the problems in below code. How will you fix it ?
char *check(int n)
{
char box[20];
sprintf(box, "%d", n);
return box;
}
Answer - box cannot be returned as it points to an array that no longer exists. One temporary fix can by declaring the box as 'static char box[20]'.

22. What is malloc's internal bookkeeping information and how does it play a role in mis-directing the location of the actual bug ?
Answer - malloc sometimes allocate one by extra rather than the actual amount of memory requested . This extra memory is the internal bookkeeping information for malloc's internal operation. Sometimes if you overwrite this area alone, it will not impact immediately, it might get affected during some other call as it has affected the bookkeeping information earlier.

23. Where would you use 'const int' instead of #define and where should you use #define instead of 'const int' ?
Answer - If you want to do more of debugging you need to use 'const int' rather than #define.
Also,if you have some memory available then you can use #define as it saves memory.
If you want to protect the variables inside the function, then it can be done by declaring the function parameters as const.

24. Keyword 'const' refers to read-only -> True/False
Answer - True

25. What is the output of the below code
#define MY_CALCULATOR 2+5+6
printf("%d \n" 3 * MY_CALCULATOR);
Answer - 17

26. How does declaring function parameters as 'const' help in better,safer code ?
Answer - It does not allow the corruption of the data inside the function.

27. Which of the following is correct . Why does point no 'i' gives output sometime & sometimes it does not give output ?
i. char *a = malloc(strlen(str));
strcpy(a, str);
ii. char *a = malloc(strlen(str) + 1);
strcpy(a, str);
Answer - Option number 'ii' is correct as strlen does not count the '\0'. So, it must be taken into consideration while allocating memory using malloc for 'a' before copying using strcpy.

28. How do the below get expanded ? Which one is the preferred method & Why ?
#define mydef struct s *
typedef struct s * mytype;
mydef d1,d2;
mytype t1,t2;
Answer - Both get expanded correctly as 'struct s *'. But, 'struct *s' applies for only the first variable in the case of '#define' and it applies for both the variables in the case of 'typedef'.

29. i. const values cannot be used in initializers - True/False
ii. const values cannot be used for array dimensions - True/False
Answer - True, True

30. Is char x[3] = "wow"; legal ?
Why does it work sometimes ?
Answer - It gives an undefined behaviour. Working fine is also a kind of undefined behaviour.

31. How will the below code corrupt stack ?
void checkstackcorruption (char *var)
{
char z[12];
memcpy(z, var, strlen(var));
}
int main (int argc, char **argv)
{
checkstackcorruption (argv[1]);
}
Answer - It has 2 important things. If the user enters more than 11 characters then it will cause stack corruption as 'z' has the capacity for only 12 characters. It is only 11 characters because it will have the '\0' at the end and strlen does not take the '\0' into consideration.

32. Is the below method of usage of realloc() correct ?
void *z = malloc(10);
free(z);
z = realloc(z, 20);
Answer - No. You should not free before reallocation.

33. What does the below mean ?
int (*)[*];
Answer - pointer to a variable length array of an unspecified number of ints,

34. The rank of any unsigned integer type shall equal the rank of the corresponding
signed integer type, if any - True/False
Answer - True

35. The rank of long long int shall be greater than the rank of long int which shall be greater than int - True/False
Answer - True

36.No two signed integer types shall have the same rank, even if they have the same
representation - True/False
Answer - True

37. sprintf function is equivalent to fprintf, except that the output is written into an array - True/False
Answer - True

38. Incase of both sprintf and fprintf , A null character is written at the end of the characters written and that is not counted as part of the returned value - True/False
Answer - True

39. Arithmetic underflow on a negative number results in negative zero - True/False
Answer - True

40.Negative zero and positive zero compare equal under default numerical comparison - True/False
Answer - True

41. 'type cast' should not be used to override a const or volatile declaration - True/False
Answer - True. Overriding these type modifiers can cause the program to fail to run correctly.

42. 'sizeof' yields the size of an array in bytes - True / False
Answer - True

43. How will you determine the number of elements in an array using sizeof operator ?
Answer - divide the size of that entire array by the size of one element of that array.

44. What is l-value & r-value ?
Answer -
In C, the term L-value originally meant something that could be assigned to (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'.
The L-value expression 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 R-value is any expression that is not an L-value, it refers to a data value that is stored at some address in memory.

45. What is the output of the below code ?
char (*x)[50];
printf("%u, %u,%d\n",x,x+1,sizeof(*x));
Answer - Address of x, Address of x + 50, 50

46.How will you declare & initialize pointer to a register located at phys addrs 600000h ?
Answer - int * pPhyRegister = (int *) 0x6000000;

47. What is NPC ?
Answer - Null Pointer Constant

48. Can we compare a pointer and integer ?
Answer - Not recommended. gcc compiler will throw a warning message if we are comparing with non-zero interger values. But, while comparing a pointer with an integer value of zero , it would consider the zero as NULL pointer constant and hence does not throw warning.

49. Why does *ps.i do not work in the below code ?
struct rec
{
int i;
float f;
char c;
};
int main()
{
struct rec *ps;
ps=(struct rec *) malloc (sizeof(struct rec));
*ps.i=10;
free ps;
return 0;
}
Answer -
It should be as (*ps).i

50. The term 'Pointer to pointer' is different from the term 'double pointer' - True/False
Answer - True.
Pointer to pointer - **a;
double pointer - double *a;

51. What is the size of a boolean variable ?
a. 1 bit
b. Depends on system memory
c. 1 byte
d. Dynamically allocated based on the memory usage by that particular program
Answer - c

52. Why does it overflow inspite of having 'long int' ?
int x = 6000, y = 6000 ;
long int z = x * y ;

Answer -
Here the multiplication is carried out between two ints x and y, and the result that would overflow would be truncated before being assigned to the variable z of type long int. However, to get the correct output, we should use an explicit cast to force long arithmetic as shown below:
long int z = ( long int ) x * y ;

53. The string function strcat( ) concatenates strings and not a character - True/False
Answer - True. The below will not work.
char str[ ] = "Hey" ;
strcat ( str, '!' ) ; // character within single quotes
But, the below will work,
char str[ ] = "Hey" ; // string within double quotes
strcat ( str, "!" ) ;

54. Function calls are allowed in initalizers for automatic variables that is local or non-static - True/False
Answer - True

55. Any number of pointers can point to the same address - True / False
Answer - True

56. Can you assign pointers to one another pointer of the same datatype ?
Answer - Yes. The address gets copied from the RHS to LHS during this assignment.

57. What is the problem in the below code ?
int main()
{
char *a;
a=(char *) malloc (100);
a="checking";
free(a);
return 0;
}
Answer -
a is pointing into the string constant table, the string cannot be changed;
But, free fails because it cannot deallocate a block in an executable region.(That is, 'a' is now pointing to a different thing completely).

57. memmove is better than memcpy - True / False.
Answer - True

58. How can will you avoid fixed-sized arrays?
Answer - Use malloc
#include
int *dynarray;
dynarray = malloc(10 * sizeof(int));
Now, you can reference dynarray[i] ('i' can be from 0 to 9).

59. Difference between memcpy and strcpy ?
Answer -
a. strcpy takes only char * as arguments.
memcpy takes void * as arguments. It can be used for arrays of any type.
a. memcpy copies the number of bytes specified.
strcpy copies until a 0 (zero) / Null character is encountered
b. memcpy replaces the whole contents in the destination.
strcpy replaces only the specific number of characters/contents got from the source. The
remaining will be present after the copied characters/contents in the destination.

60. What does the below code do ?
i. x = x+y; y = x-y; x = x-y;
ii. x = x^y; y = x^y; x = x^y;
Answer - Both perform swapping of values of x and y.

61. What will be present in box2 and how to overcome the problem ?
#define LEN 10
char box1[LEN] = "c";
char box2[LEN] = "_Quest";
strcpy(box2,box1);
Answer - box2 will have 'cQuest' . Use memcpy to avoid the box2 from having the other unnecessary stuffs at the end after strcpy.

62.

70. What is the output of the below code ?
int main(void)
{
int a[]={ 11,22,33,44,55};
char*p=(char*)a;
printf("%d", * ( (int *) p+4));
return 0;
}
Answer - 55

71. In the below code, what is the alternative for (*p).i ?
struct rec *p;
(*p).i=10;
Answer - p->i=10

72. What is the output of below code ?
p = 0;
*p = 5;
Answer -
This demonstrates the problem due to dereferencing a zero pointer reference.
The program will normally crash. The pointer p does not point to any block, it points to zero, so a value cannot be assigned to *p. The system will generate error messages if you happen to dereference a zero pointer.

73. Why does this program crash sometimes only ?
int *p;
*p = 8;
Answer -
This is a famous example for demonstrating the problems with uninitialized pointer.
When you say *p=8;, the program will simply try to write a 8 to whatever random location p points to. But, the pointer p is uninitialized and points to a random location in memory when you declare it. It could be pointing into the system stack, or the global variables, or into the program's code space, or into the operating system. The program may explode immediately, or may wait half an hour and then explode, or it may subtly corrupt data in another part of your program and you may never realize it. This can make this error very hard to track down. Make sure you initialize all pointers to a valid address before dereferencing them.

74. The inline directive will be totally of no use when used for functions that are -
i. recursive
ii. long
iii. composed of loops
iv. All of the above
Answer - iv

75. What is the difference between Inline and Macro ?
Answer -


Credit - C-FAQ, C discussion groups & internet.

No comments:

Post a Comment