Tuesday, 14 March 2017

C programming

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

#include <stdio.h>
int main()
{
 char a=10;
 char b=13;
   char const* p1;         //The Value of P1 Cant be changed
   char *const p2=&b; //Cant be changed the P2
   p1=&a;
   a=11;
   p1=&b;
   b=15;
    printf("Hello, World! %d\n",*p2);
    printf("Hello, World! %d\n",*p2);

    return 0;
}

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

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

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

When does the compiler not implicitly generate the address of the first element of an array? Whenever an array name appears in an expression such as - array as an operand of the sizeof operator - array as an operand of & operator - array as a string literal initializer for a character array Then the compiler does not implicitly generate the address of the address of the first element of an array.

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

What is the difference between text and binary modes?
Streams can be classified into two types: text streams and binary streams. Text streams are interpreted, with a maximum length of 255 characters. With text streams, carriage return/line feed combinations are translated to the newline n character and vice versa. Binary streams are uninterrupted and are treated one byte at a time with no translation of characters. Typically, a text stream would be used for reading and writing standard text files, printing output to the screen or printer, or receiving input from the keyboard. A binary text stream would typically be used for reading and writing binary files such as graphics or word processing documents, reading mouse input, or reading and writing to the modem.

What is static memory allocation and dynamic memory allocation? 
Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator,the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. memory is assigned during compilation time. Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically.If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation.memory is assined during run time.

When should a far pointer be used? 
Sometimes you can get away with using a small memory model in most of a given program. There might be just a few things that don’t fit in your small data and code segments. When that happens, you canuse explicit far pointers and function declarations to get at the rest of memory. A far function can be outside the 64KB segment most functions are shoehorned into for a small-code model. (Often, libraries are declared explicitly far, so they’ll work no matter what code model the program uses.) A far pointer can refer to information outside the 64KB data segment. Typically, such pointers are used with farmalloc() and such, to manage a heap separate from where all the rest of the data lives. If you use a small-data, large-code model, you should explicitly make your function pointers far.

How are pointer variables initialized? 
Pointer variable are initialized by one of the following two ways - Static memory allocation - Dynamic memory allocation

Difference between arrays and pointers? 
 Pointers are used to manipulate data using the address. Pointers use * operator to access the data pointed to by them - Arrays use subscripted variables to access and manipulate data. Array variables can be equivalently written using pointer expression.

Is using exit() the same as using return? 
No. The exit() function is used to exit your program and return control to the operating system. The return statement is used to return from a function and return control to the calling function. If you issue a return from the main() function, you are essentially returning control to the calling function, which is the operating system. In this case, the return statement and exit() function are similar.

What is indirection? 
If you declare a variable, its name is a direct reference to its value. If you have a pointer to a variable, or any other object in memory, you have an indirect reference to its value.

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

How many levels deep can include files be nested? 
Even though there is no limit to the number of levels of nested include files you can have, your compiler might run out of stack space while trying to include an inordinately high number of files. This number varies according to your hardware configuration and possibly your compiler.

What is the difference between declaring a variable and defining a variable? 
Declaring a variable means describing its type to the compiler but not allocating any space for it. Defining a variable means declaring it and also allocating space to hold the variable. You can also initialize a variable at the time it is defined.

What is an lvalue? 
An lvalue is an expression to which a value can be assigned. The lvalue expression is located on the left side of an assignment statement, whereas an rvalue is located on the right side of an assignment statement. Each assignment statement must have an lvalue and an rvalue. The lvalue expression must reference a storable variable in memory. It cannot be a constant.

Differentiate between an internal static and external static variable? 
An internal static variable is declared inside a block with static storage class whereas an external static variable is declared outside all the blocks in a file.An internal static variable has persistent storage,block scope and no linkage.An external static variable has permanent storage,file scope and internal linkage.

What is an argument?
 Differentiate between formal arguments and actual arguments? An argument is an entity used to pass the data from calling function to the called function. Formal arguments are the arguments available in the function definition. They are preceded by their own data types. Actual arguments are available in the function call.

What are advantages and disadvantages of external storage class? 
Advantages of external storage class 1)Persistent storage of a variable retains the latest value 2)The value is globally available Disadvantages of external storage class 1)The storage for an external variable exists even when the variable is not needed 2)The side effect may produce surprising output 3)Modification of the program is difficult 4)Generality of a program is affected

What is a void pointer?
 A void pointer is a C convention for a raw address. The compiler has no idea what type of object a void Pointer really points to. If you write int *ip; ip points to an int. If you write void *p; p doesn’t point to a void! In C and C++, any time you need a void pointer, you can use another pointer type. For example, if you have a char*, you can pass it to a function that expects a void*. You don’t even need to cast it. In C (but not in C++), you can use a void* any time you need any kind of pointer, without casting. (In C++, you need to cast it). A void pointer is used for working with raw memory or for passing a pointer to an unspecified type. Some C code operates on raw memory. When C was first invented, character pointers (char *) were used for that. Then people started getting confused about when a character pointer was a string, when it was a character array, and when it was raw memory

When should a type cast not be used? 
A type cast should not be used to override a const or volatile declaration. Overriding these type modifiers can cause the program to fail to run correctly. A type cast should not be used to turn a pointer to one type of structure or data type into another. In the rare events in which this action is beneficial, using a union to hold the values makes the programmer’s intentions clearer

When is a switch statement better than multiple if statements? 
A switch statement is generally best to use when you have more than two conditional expressions based on a single variable of numeric type.

What is a static function?
 A static function is a function whose scope is limited to the current source file. Scope refers to the visibility of a function or variable. If the function or variable is visible outside of the current source file, it is said to have global, or external, scope. If the function or variable is not visible outside of the current source file, it is said to have local, or static, scope.

What is a pointer variable? 
A pointer variable is a variable that may contain the address of another variable or any valid address in the memory

What is a pointer value and address?
 A pointer value is a data object that refers to a memory location. Each memory location is numbered in the memory. The number attached to a memory location is called the address of the location

What is a modulus operator? What are the restrictions of a modulus operator?
 A Modulus operator gives the remainder value. The result of x%y is obtained by (x-(x/y)*y). This operator is applied only to integral operands and cannot be applied to float or double.

Differentiate between a linker and linkage?
 A linker converts an object code into an executable code by linking together the necessary build in functions. The form and place of declaration where the variable is declared in a program determine the linkage of variable.

What is a function and built-in function? 
A large program is subdivided into a number of smaller programs or subprograms. Each subprogram specifies one or more actions to be performed for a large program. such subprograms are functions. The function supports only static and extern storage classes. By default, function assumes extern storage class. functions have global scope. Only register or auto storage class is allowed in the function parameters. Built-in functions that predefined and supplied along with the compiler are known as built-in functions. They are also known as library functions.

Why should I prototype a function?
 A function prototype tells the compiler what kind of arguments a function is looking to receive and what kind of return value a function is going to give back. This approach helps the compiler ensure that calls to a function are made correctly and that no erroneous type conversions are taking place.


Implement your own sizeof operator using bitwise operation .
#include <stdio.h>
#define type long double
int size_of(type n)
{
 type *p = &n;
 return ((unsigned int)(p+1) - (unsigned int)p);
}
 
int main(void) {
 type x = 12;

 printf("%d", size_of(x));
}


When is that we we want to use "user virtual address" instead of "kernel virtual address"? List some situations when we cannot go with kernel virtual address.
Obviously, when we are running a program in userspace, we don't have access to the kernel virtual memory addresses. In that situation, the question is moot. 

When we are running code in kernel mode, say, as a kernel module or driver, we normally access kernel virtual memory. But if the situation comes where our kernel mode code has to interact with some userspace component, we must be extremely careful that we translate "kernel virtual addresses" to "user virtual addresses" before passing them off, and vice-versa.
Which one is faster and why?
1. Array
2. Link List.
If we just want to iterate in for loop and print it.
Array Elements are stored in contiguous memory locations. Hence they will be faster to retrieve.
How can you tell if your system is little endian or big endian?
#include<stdio.h>

int main()
{
  int a = 1;
  char *b;

  b = (char *)&a;
  if (*b)
    printf("Little Endian\n");
  else
    printf("Big Endian\n");
}

As kernel can access user space memory, why should copy_from_user is needed?
one of the major requirement in system call implementation is to check the validity of user parameter pointer passed as argument, kernel should not blindly follow the user pointer as the user pointer can play tricks in many ways. Major concerns are: 1. it should be a pointer from that process address space - so that it cant get into some other process address space. 2. it should be a pointer from user space - it should not trick to play with a kernel space pointer. 3. it should not bypass memory access restrictions. 

that is why copy_from_user() is performed. It is blocking and process sleeps until page fault handler can bring the page from swap file to physical memory.
how function pointers are shared across different processes? using which iPCs?
two processes can not share function pointers. 
if you want to use functions in two processes make library for that functions 
and use that library in your processes.
how a function from one user process can be called in other user process?
Use Remote Procedure Calls (RPC) to call functions in another process
Difference between kill -9 and kill -3
-3 interrupt like ctrl-\ u can consider it as an error signal 
-9 kill force the process to be killed

What is multithreading
The ability of an operating system to execute different parts of a program, "called threads", simultaneously is called multithreading. The programmer must carefully design the program in such a way that all the threads can run at the same time without interfering with each other. Multithreading aims to increase utilization of a single core by using thread-level as well as instruction-level parallelism.

What is the difference between a string and an array? 


  1. Strings as arrays:Before the string class, the abstract idea of a string was implemented with just an array of characters. For example, here is a string:
    char label[] = "Single";
    
    What this array looks like in memory is the following:
    ------------------------------
    | S | i | n | g | l | e | \0 |
    ------------------------------
    
    where the beginning of the array is at some location in computer memory, for example, location 1000.

    Note: Don't forget that one character is needed to store the nul character (\0), which indicates the end of the string.
    A character array can have more characters than the abstract string held in it, as below:
    char label[10] = "Single";
    
    giving an array that looks like:
    ------------------------------------------
    | S | i | n | g | l | e | \0 |   |   |   |
    ------------------------------------------
    
    (where 3 array elements are currently unused).
    Since these strings are really just arrays, we can access each character in the array using subscript notation, as in:
    cout << "Third char is: " << label[2] << endl;
    
    which prints out the third character, n.A disadvantage of creating strings using the character array syntax is that you must say ahead of time how many characters the array may hold. For example, in the following array definitions, we state the number of characters (either implicitly or explicitly) to be allocated for the array.
    char label[] = "Single";  // 7 characters
    
    char label[10] = "Single";
    
    Thus, you must specify the maximum number of characters you will ever need to store in an array. This type of array allocation, where the size of the array is determined at compile-time, is called static allocation.
  2. Strings as pointers:Another way of accessing a contiguous chunk of memory, instead of with an array, is with a pointer.
    Since we are talking about strings, which are made up of characters, we'll be using pointers to characters, or rather, char *'s.
    However, pointers only hold an address, they cannot hold all the characters in a character array. This means that when we use a char * to keep track of a string, the character array containing the string must already exist (having been either statically- or dynamically-allocated).
    Below is how you might use a character pointer to keep track of a string.
    char label[] = "Single";
    char label2[10] = "Married";
    char *labelPtr;
    
    labelPtr = label;
    
    We would have something like the following in memory (e.g., supposing that the array label started at memory address 2000, etc.):
    label @2000
    ------------------------------
    | S | i | n | g | l | e | \0 |
    ------------------------------
    
    label2 @3000
    ------------------------------------------
    | M | a | r | r | i | e | d | \0 |   |   |
    ------------------------------------------
    
    labelPtr @4000
    --------
    | 2000 |
    --------
    


    Note: Since we assigned the pointer the address of an array of characters, the pointer must be a character pointer--the types must match.Also, to assign the address of an array to a pointer, we do not use the address-of (&) operator since the name of an array (like label) behaves like the address of that array in this context.

    Now, we can use labelPtr just like the array name label. So, we could access the third character in the string with:
    cout << "Third char is: " << labelPtr[2] << endl;
    
    It's important to remember that the only reason the pointer labelPtr allows us to access the label array is because we made labelPtr point to it. Suppose, we do the following:
    labelPtr = label2;
    
    Now, no longer does the pointer labelPtr refer to label, but now to label2 as follows:
    label2 @3000
    ------------------------------------------
    | M | a | r | r | i | e | d | \0 |   |   |
    ------------------------------------------
    
    labelPtr @4000
    --------
    | 3000 |
    --------
    
    So, now when we subscript using labelPtr, we are referring to characters in label2. The following:
    cout << "Third char is: " << labelPtr[2] << endl;
    
    prints out r, the third character in the label2 array.



Singly Linked list

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

struct node {
    int data;
    struct node *next;
};
struct node *head;

int initilize(void){
    head=(struct node *)malloc(sizeof (struct node));
    head->data=0;
    head->next=NULL;
}

int display(struct node *head){
    if(head==NULL)
        printf("No data avaliable\n");
    else{
        while(head !=NULL){
        printf("%d ",head->data);
        head=head->next;
        }
        printf("\n");
    }
}

int insert(struct node *head,int val)
{
    struct node *temp=(struct node *)malloc(sizeof (struct node));
    temp->data=val;
    temp->next=NULL;

    while(head->next != NULL){
    head=head->next;
    }
    head->next=temp;
}

struct node * delete_first(struct node *head)
{
    if(head==NULL)
        printf("No data avaliable\n");
    else{
        head=head->next;
    }
    return head;
}
struct node * delete(struct node *head,int val)
{
    if(head==NULL)
        printf("No data avaliable\n");
    else{
        while(head->data!=val){
           
        }
        head=head->next;
    }
    return head;
}

int main()
{
    printf("Hello, World!\n");
    initilize();
    display(head);
    insert(head,10);
    insert(head,20);
    insert(head,30);

    display(head);
    head=delete_first(head);
    display(head);
    head=delete_first(head);
    display(head);
   
    return 0;
}