C cheat Sheet - Part 1

General:

  1. ++ or -- cannot be used on enum value.
  2. sprintf could be used to convert an int or float to a string
  3. free() frees the memory during run time
  4. fflush() flushed all the streams and the specified streams.
  5. randomize(): returns a random number generator with a random value based on time.
  6. fprintf- Can be used to print the output to the screen.
  7.  '\o' is called as NULL in AScii
  8. ftell() tells the current position in the file stream
  9. frewind() goes to the start of the file.
  10. The C standard library consists of a set of sections of the ISO C standard which describe a collection of header files and library routines used to implement common operations, such as input/output and string handling, in the C programming language. The C standard library is an interface standard described by a document; it is not an actual library of software routines available for linkage to C programs.
  11. Hence, standard library is not a part of C package.
  12. fmod performs floating point divisions. Hence you cannot use % operator on the float.
  13. Types of linkages: Internal, External, and None
  14. By Default a real number is treated as double
  15. If we use extern as a qualifier then we should declare it outside.
  16. Any pointer size is 2 bytes. (only 16-bit offset)
    1. a.     So, char *s1 = 2 bytes.
    2. b.     So, char far *s2; = 4 bytes.
    3. c.     So, char huge *s3; = 4 bytes.
  17. A far, huge pointer has two parts: a 16-bit segment value and a 16-bit offset value.
  18. Since C is a compiler dependent language, it may give different at different platforms. The above program works fine in Windows (TurboC), but error in Linux (GCC Compiler).
  19. When an automatic structure is partially initialized remaining elements are initialized to 0(zero).
  20. When an automatic array is partially initialized, the remaining elements are initialized to 0
  21. Yes, In all the global variable declarations, you need to use the keyword extern. And it has only one definition
  22. In 16 bit compiler, the pointer size is always 2 bytes.
  23. In 32 bit compiler, the pointer size is always 4 bytes.
  24. sizeof(3.14f) here '3.14f' specifies the float data type. Hence size of float is 4 bytes
  25. sizeof(3.14) here '3.14' specifies the double data type. Hence size of float is 8 bytes.
  26. sizeof(3.14l) here '3.14l' specifies the long double data type. Hence size of float is 10 bytes.
  27. Recurrence relations are used to find the big Oh of the recursive functions
  28. Bitwise & can be used in conjunction with ~ operator to turn off 1 or more bits in a number.
  29. 16-bit compiler will generate the machine code that is targeted to work for 16-bit microprocessor
  30. Highest bit is used to store the sign of the integer.
  31. Long int/ long(Atleast 4)
    1. Short int/short (atleast 2 bytes)
    2. Ints never bigger than longs
  32. If the constant value is small to be satisfied by int but we want more storage so we can have
    1. a.     Int I = 23L.          //This will assign more space to it.
  33. Signed and unsigned:
    1. Signed int i
    2. Signed I; //Default is signed.
  34. Signed and unsigned int;
  35. Signed and unsigned char;
  36. Signed and unsigned float
  37. In case of signed if we assign a character that has int value greater than 127 then rollover happens and value from the other side gets assigned to it.
    1. When we attempted to store 128 in char then the negative value get stored in char\
    2. If we exceed range on positive side we end up on negative side and vice versa.
  38. Int has 2/4 bytes of memory.
  39. Long = 4 bytes of memory
  40. Short = 2 bytes of memory
  41. Float = 4 bytes of memory
  42. Double = 8 bytes of memory
  43. Char = 1 bytes of memory
  44. Long double = 10 bytes
  45. Data types: Summary
    1. Signed int
    2. Unsigned int
    3. Short signed int
    4. Short unsigned int
    5. Long signed int
    6. Long unsigned int
    7. Signed char
    8. Unsigned char
    9. Float
    10. Double
    11. Long double
  46. The size of int, char, float is compiler dependent
  47. The negative numbers are stored in 2C format.
  48. FILE - a structure containing the information about a file or text stream needed to perform input or output operations on it, including:
    1. a file descriptor, the current stream position,
    2. an end-of-file indicator,
    3. an error indicator,
    4. a pointer to the stream's buffer, if applicable
Functions:

  1. In functions there is no precedence
  2. main() can be called from some other functions.
    1. For ex: a() { main()}
  3. One function cannot be defined in another
  4. Each function perform some isolated task.
  5. 2 types of functions:
    1. Library - Same type of functions are grouped together
      1. They reside on the disk.
      2. Written by people, who write compilers 
    2. User Defined
  6. The number, type, and order of formal and actual arguments should be same.
  7. They(Actual & Formal) are treated as different by the compiler.
  8. return; //It will return the garbage values
  9. return(10,20); //Not allowed
  10. Pass by value:
  11. When the formal arguments are passed to the actual arguments. Then the arguments are not passed. Only the photocopy is passed.
  12. Formal arguments and local variables are defined inside the stack.
  13. Standard Calling convention:
    1. Arguments are passed in the Right to Left order.
  14. func(int a, int b)
    1. func(1,2); => b = 2 && a = 1
  15. Stack is cleaned up by the called function: For ex:
    1. Main() { Func(); //This function cleans up the stack }
  16. If the return type is not specified then int is assumed by default.
  17. The address cannot be negative. Hence, we can’t have sign associated with it. Hence %u.
  18. **p: A pointer, which contains another pointer address, which in turn contain the address of either int/char/float.
  19. Address are always whole numbers. Hence pointers cannot have floating point numbers.
  20. Compilers use stack for normal and recursive function calls.
  21. Whenever, we make a recursive calls. The parameters and the return address get pushed to the stack
  22. If we don’t have a base condition for the function then soon the stack will overflow and runtime error: stack overflow will come.
  23. Whenever, we compile the code we get object file. .c to .obj
Data Types:

  1. 16-bit compiler will generate the machine code that is targeted to work for 16-bit microprocessor
  2. Highest bit is used to store the sign of the integer.
  3. Long int/ long(Atleast 4)
    1. Short int/short (atleast 2 bytes)
    2. Ints never bigger than longs
  4. If the constant value is small to be satisfied by int but we want more storage so we can have
    1. Int I = 23L.          //This will assign more space to it.
  5. Signed and unsigned:
    1. a.     Signed int i
    2. b.     Signed I; //Default is signed.
  6. Signed and unsigned int;
  7. Signed and unsigned char;
  8. Signed and unsigned float
  9. In case of signed if we assign a character that has int value greater than 127 then rollover happens and value from the other side gets assigned to it.
    1. When we attempted to store 128 in char then the negative value get stored in char\
    2. If we exceed range on positive side we end up on negative side and vice versa.
  10. Int has 2/4 bytes of memory.
  11. Long = 4
  12. Short = 2
  13. Float = 4
  14. Double = 8
  15. Char = 1
  16. Long double = 10 bytes
  17. Data types: Summary
    1. Signed int
    2. Unsigned int
    3. Short signed int
    4. Short unsigned int
    5. Long signed int
    6. Long unsigned int
    7. Signed char
    8. Unsigned char
    9. Float
    10. Double
    11. Long double
  18. The size of int, char, float is compiler dependent
  19. The negative numbers are stored in 2C format.

Storage Class:

  1. It specifies where the value of the variable should be stored.
    1. Memory or CPU registers.
    2. Storage class defines it.
  2. Types of storage classes:
    1. Auto
    2. Static
    3. Extern
    4. Register
  3. Storage class specifies:
    1. Location of variable
    2. Initial value
    3. Scope
    4. Life
  4. Auto:
    1. Location: Memory
    2. Initial value: Garbage if not assigned
    3. Scope: Local
    4. Life: Till the control remains in the block, where it is defined.
  5. Static:
    1. Location: Memory
    2. Initial value: Zero
    3. Scope: Local
    4. Life: Persists between function calls.
    5. Avoid it unless you absolutely needs them. They are stored in the memory and use up space even when they are  active.
    6. They get defined in the data segment. Die only when program execution comes to an end.
  6. Registers:
    1. Location: CPU Register
    2. Value: Garbage
    3. Scope: Local to the block
    4. Life: Till the control remain in block
    5. Same as auto only it is defined in the registers
  7. Extern:
    1. Location: Memory
    2. Value: Zero
    3. Scope: Global
    4. Life: Till the program execution comes to end.
    5. They are available in other files too where they are not declared
    6. Example:   Int main( { Extern int I  } int I =10;
  8. Static variable can be defined outside all the functions and it will be available to all functions. But it will not be available to other functions in other file.

C++ Cheat Sheet

1) If a class has a virtual function and we create an instance of the derived class without the pointer then there will be unresolved dependencies.

2) We have to use the:

shape *s = new shape();
In the above statement shape() calls the constructor.
If the values are defined by the constructor then the values should be given the constructor shape(10,10), etc.

3) If the virtual function is not defined in the derived class then the base class's virtual function is used. 


4) If the inheritance is used then pointer type as well as normal variable type both should be used.


5) If the constructor with parameters is used then the default constructor should also be used.


6) If the constructor is declared in the private section then it cannot be accessed. 


7) If you try to create an instance of the abstract class then the program will not compile.


8) Creating abstract class

 class A
{
     public:
     virtual void display() = 0;
};


9) If the derived class doesn't define the virtual function then it will become abstract class too.

If we try to instantiate it then it will give compile time error.

10) String class of C++
In C++ you don't need to implement default functions like finding its length, finding a specific character, replacing characters etc. String class is a library that comes with a variety of functions. Following is some code. Each function is followed by its description. 
string s("BB");
string r = "R";
//copy, cbegin, cend, crbegin, crend, c_str, 
//get_allocator, max_size, npos, rbegin, rend, 
//replace, reserve, shrink_to_find, substr, swap
      
s.append(1,'a'); //1 specifies that 'a' to be appended once
      
s.assign(1,'b'); //Replaces entire string "BB" to B. 1 over here specifies that it will only be assigned only once.
      
char ch = s.at(2); //It specifies which character is availabe at location 2
      
ch  = s.back(); //It specifies that the character present at the last location
string::iterator it; //Iterator
it = s.begin(); //begin and end function both are used with the iterator
it = s.end();
      

int i = s.capacity(); //It specifies the characters that can fit into that string. Remember capacity concept of vector or dynamic array
      
s.clear(); //It will delete all the characters from the string but not the string.
      
i = s.compare(s); //It compares 2 strings. If equal then it returns 0 and o/w returns -1
      
string s1 = s.data(); //It will copy one string to another
      
i = s.empty(); //It will tell you if the string is empty or not. If the string is empty it will return 1 else 0.
      
s.erase(); //It is brother of clear. It will erase all the characters from the string.
      
i = s.find('a'); //It will find the location of a specific character in the string.
      
i = s.find_first_not_of('B'); //It will find the location where the character is not 'B' after the first occurence of 'B'
//In the string the above function will return 1. Since 'h' is first character where 'B' is not appearing

i = s.find_first_of('B');

i = s.find_last_not_of('B'); //It starts from the end

i = s.find_last_of('B');

ch = s.front(); //It gives the first character appearing the string

s.insert(1,1,'b'); //It will insert the character b once in the string at location 1
      
i = s.length(); //Doesn't count the NULL as the strings of C++ are not null-terminated

s.pop_back(); //It will pop the last character from the string and decrese the string length

s.push_back('a'); //Adds a character at the end of the string

s.resize(20); //It will increase its length and simultaneoulsy the capacity will be increased too
      
i = s.rfind('B'); //Finds the string but starts from the end.
      
i = s.size(); //It gives the size of the string

11) Deque: It is another data structure of C++ that has some defined functions. It is a double ended queue where insertion and deletion are allowed from both the sides. Following code snippet explains different functions.

deque d;
deque::iterator it;d.assign(1,10); //It will allocate a deque of size 1 and value 10
 
d.get_allocator().allocate(5); //It will allocate the space of 5 variables
 
d.erase(d.begin() + 1); //It will erase the data present at location 1
 
d.insert(d.begin()+1, 100); //It will insert the data at the location v.begin()+1
 
d.assign(2,20); //It will increase the size to 2 and both places will have value 20s
d.assign(3,30);
 
int i = d.at(0); //Outputs the number present at that location
 
i = d.back(); //Gives the last number as output
 
//d.clear(); //Cleares the contents of the deque
 
i = d.empty(); //It returns 0 if the deque is empty or else 1
 
i  = d.front(); //It will outputs the value present at the front
 
i = d.max_size(); //Gives the max size that the deque could occupy
 
d.pop_back(); //deletes the last element
 
d.pop_front(); //deletes the front element
 
d.push_back(10); //Adds an element to the front of the queue
 
d.push_front(10); //Adds an element to the end of the queue
 
d.resize(10);//Resizes the deque
 
i = d.size(); //Gives the size of the queue
 
12) Void Pointer: It is a generic pointer that can point to an object or memory location of any data type. 
void *p;
char c = 'c';
int i = 10;

p = &i; //void pointer p pointer to an int type now. We can’t just deference it. We need another pointer that will point to it and then that pointer can be dereferenced.
int *p1; //Some other int pointer
p1 = (int*)p; //Another int pointer now points to the address the pointed by void pointer
 
p = &c; //void pointer now points to the char type
 
char *c1; //Some other char pointer
c1 = (char*)p; //Another char pointer points to the address pointed by the void pointer
//Hence we can use the void pointer to point to different data types now.
 
cout << *p1 << endl;
cout << *c1 << endl;

13) List class in C++. List class is internally implemented as DLL. It allows insertion and deletion from both sides of the list in O(n) time. 


list l; //Creating a list
    
 list l; //Creating a list
list::iterator it; //Iterator for the list
 
it = l.begin(); //Initializing the iterator
 
for(i = l.begin();i!=l.end();i++) //Traversing the list
       cout << *i << endl;

      
//Opertions: pop_back, pop_front, push_back, push_front, insert, 
//assign, back, empty, end, erase, front, resize, reverse, 
//sort, swap, unique, splice.

14) Vector class in C++. It is similar to arrays in C++ but they can change size dynamically. Arrays are constant in size that doesn't change size once its capacity is reached. 
vector v;
vector v; //Vector
 v.push_back(20); //Adding data to the vector
 v.push_back(10);
 v.push_back(30);

 vector::iterator it; //Iterator for the vector

 for(it=v.begin();it!=v.end();it++) //Moving from start to end for the vector
 {
  cout << *it << endl;
 }


Basics of Kernel

General
Kernel is divided into layers:
  1. Electronics like electronics, I/O, CPU, memory, disk controllers, network controllers, user peripherals
  2. Hardware interfaces: Devices access and bus drivers, CPU specific, physical memory operations, disk controllers drivers, network device drivers, HI peripherals device drivers
  3. Device control: Generic HW access, Interrupt context, Page allocator, Block devices, Virtual network device, abstract devices and HID class drivers
  4. Funtional: system run, Schedular, logical memory, Logical file systems, protocols, HI subsytems
  5. Bridges: Synchronization, Memory mapping, Page Cache and Swap, Networking storage,
  6. Virtual: Device model, threads, virtual memory, virtual file system, protocol families,
  7. user space interfaces: system interfaces, processes, memory access, file and directories access, sockets access, HI char devices
  8. functions layers: system, processing, memory, storage, networking, human interface.


Architecture:
  1. Device drivers and kernel extensions run in kernel space - ring 0 with full access to the H/W.
  2. Some exceptions run in user space.
  3. Kernel is also called as core, internal, and supervisior.
  4. Kernel Space includes System state and memory space.
  5. Applications running on the system communicate with the kernel via the system call.
  6. An application typically calls functins in a library for example, the C library that in turn rely on the system call interface to instruct the kernel to carry out tasks on their behalf.
  7. Some library calls provide many features not found in the system call, thus calling into the kernel is just one step in an otherwise large function.
  8. The applications call into the kernel via the system call interface is the fundamental manner in which the application get work done.
  9. The processor is done one of the three things at any given moment:
  10. In kernel space, in process context, executing on behalf of a specific process
  11. In kernel space, in interrupt context, not associated with a process, handling an interrupt
  12. In user-space, executing user code in a process


Monolithic kernels Versus Microkernel Designs:
  1. Monolithic kernels: Implemented entirely as a singel large processes running entirely in a singel address space. They typically exist on disk assingle static binaries. Communication within kernel is trivial.  
  2. Linux is monolithic. It has some features of the microkernel like: modular design with kernel preemption, kernel threads, dynamically load separate binaries into the kernel.
  3. Microkernel: The functionality of the kernel is broken down into separate processes, usually called servers. Direct funtion invocation is not possible. An IPC is built into the system and the varios servers communicate and invoke 'Services'. Their is an overhead in this mechanism.


How are Linux kernel Versions defined?
  1. 2.6.0
  2. 2 is the major release
  3. 6 is the minor release. Even means it is stable and odd means it is in the development stage.
  4. 0 is the patch level


Installation
  1. tar xvjf linux-x.y.z.tar.bz2 //for bzip2
  2. tar xvzf linux-x.y.z.tar.gz //for GNU zip


Using patches:
patch -p1 < ../patch-x.y.z


Kernel Features:
  1. coded in GNU C
    1. Inline functions: It makes the code efficient because the function invocation and return are saved making optimizations because the compiler can optimize the caller and the called    function together.
    2. For large sized functions it becomes an overhead because memory consumption and instruction cache footprint increases.
    3. It is declared as:
      1. static inline void abc(unsigned long var1)
    4. They are commonly included in the header files.
    5. They are type safe as compared to macros
    6. gcc c compiler enables the embedding of assembly instructions in normal C functions. It is used in those parts of the kernel that are unique to system architecture.
    7. asm() compiler directive is used to inline assembly code.
    8. gcc c compiler directive divides the conditional branches as very likely or unlikely taken. 2 macros like: likely() and unlikely()
if(unlikely(f00)
{
/*------*/
}


if(likely(foo))
{
/*--------*/
}


Performance boost when the branch is predicted correctly or loss when it is predicated uncorrectly.


  1. Lacks memory protection like user-space
    1. For a user process error the kernel can trap the error, send SIGSEGV, and kill the process.
    2. If kernel does any error then there is no one to look out.


  1. Cannot easily use floating point


  1. Has a small fixed size stack
    1. The kernel stack is fixed in size and is small. Stack size varies by architecture.
    2. Stack is configure at compile time and is either 4 or 8kb
    3. It is of 2 pages, 8KB on 32 bit architecture and 16KB on 64 bit architecture


  1. Synchronization and concurrency are major concerns.
    1. Kernel is vulnerable to race conditions.
    2. Linux kernel supports multiprocessing. Without proper protection, kernel code executing on two or more processes can access the same resource
    3. Solution: Semaphores and spinlocks


  1. Portability - C code is architecture independent.


  1. Does not have access to the C library
    1. Reason is space and speed.
    2. Many of the usual libc functions have been implemented inside the kernel. EX: lib/string.c <linux/string.h>
    3. Kernel source files cannot use outside source files because it cannot include them.
    4. printk() is used in place of printf(). It copies the formatted string into the kernel log buffer, which is normally read by the syslog program. Allows to use the priority flag, which is used         by syslogd(8) to decide where to display kernel messages.






NoSQL

NoSQL Data models: key-value  Aggregate model.  key or id is used to get the data.  Lookup is based on the key.   document Aggre...