Thursday, July 31, 2014

make linux easy

List of useful inux command which i came across

1. ctrl + r     to know the old commands typed
2. !ca    this execute old executed cat command
a. first typed    gdb ../test.out
b. !gd    to execute above command
3a. to create the new command in the linux using /etc/bashrc file:
example:

-> my new command "lsf" tells the output of the 3 commands:
-> Add this command at the end of the /etc/bashrc file
function lsf
{
        ls -ltrh | more
        ls | wc
        date
}

3b. or another way to create new command:

a. put necessary command in one file.
b. then change its mode and copy into /bin. so you can access from anywhere in the linux prompt
ex:
[root@localhost ~]# cat mycmd
killall -9 telnet
ps -aH
[root@localhost ~]# chmod 777 mycmd
[root@localhost ~]# cp mycmd /bin/
[root@localhost ~]# cd /home/
[root@localhost home]# mycmd
telnet: no process killed
  PID TTY          TIME CMD
32199 pts/42   00:00:00 vim
 1958 pts/40   00:00:00 vim
 1971 pts/39   00:00:00 vim
12485 pts/55   00:00:01 vim
12486 pts/55   00:00:00   cscope


4. how to use cscope?
a. #cscope -uR    for first time
b. #cscope -d        for next time to use exisiting cscope.out file

Tuesday, July 29, 2014

bit programming techniques


we going to see simple formulas which makes life easy using bit programming

Truth table:


Logic 1: to check number is even or odd
 
Number is divisible by 2
 
 /*Masking the LSB 0000 0001. decimal value = 1*/
if ((x & 1) == 0) {
  x is even
}
else {
  x is odd
}

Number is divisible by 4 
/*Masking the LSB 0000 0011. decimal value = 3*/
if ((x & 3) == 0) {
  x is divisible by 4
}
else {
  x is not divisible  by 4
}

Number is divisible by 8
/*Masking the LSB 0000 0111. decimal value = 7*/
if ((x & 7) == 0) {
  x is divisible by 8
}
else {
  x is not divisible  by 8
}

Number is divisible by 16
/*Masking the LSB 0000 1111. decimal value = 15*/
if ((x & 15) == 0) {
  x is divisible by 16
}
else {
  x is not divisible  by 16
}


Number is divisible by 32
/*Masking the LSB 0001 1111. decimal value = 31*/
if ((x & 31) == 0) {
  x is divisible by 32
}
else {
  x is not divisible  by 32
}

Number is divisible by 64
/*Masking the LSB 0011 1111. decimal value = 63*/
if ((x & 63) == 0) {
  x is divisible by 64
}
else {
  x is not divisible  by 64
}

Number is divisible by 128
 
/*Masking the LSB 0111 1111. decimal value = 127*/
if ((x & 239) == 0) {
  x is divisible by 128
}
else {
  x is not divisible  by 128
}



Logic 2: test nth bit of any number

if (x & (1<<n)) {
  n-th bit is set
}
else {
  n-th bit is not set
}

or

To check a bit, shift the number x to the right, then bitwise AND it:
  1. bit = (number >> x) & 1;
Logic 3set the nth bit of given number

y = x | (1<<n)

Logic 4: unset the nth bit of given number

y = x & ~(1<<n)

Logic 5: Toggle the n-th bit. (or just do opposite. if upper then lower  or if lower then upper)

 
y = x ^ (1<<n)



Main source:  http://www.catonmat.net/blog/low-level-bit-hacks-you-absolutely-must-know/


Logic 6: Multiplication and division

expr1 << expr2 (2 * 4 == 2 << 2) 
is equivalent to multiplication by 2expr2
expr1 >> expr2  (8 / 4 == 8 >> 2)
is equivalent to division by 2expr2 
Logic 7 : check whether the number is power of 2 or not:

 If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.
For example for 4 ( 100) and 16(10000), we get following after subtracting 1
3 –> 011
15 –> 01111
So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1))

#include<stdio.h> 
#define bool int 

/* Function to check if x is power of 2*/ 
bool isPowerOfTwo (int x) 
{ 
/* First x in the below expression is for the case when x is 0 */ 
return x && (!(x&(x-1))); 
} 
/*Driver program to test above function*/ 
int main() 
{ 
isPowerOfTwo(31)? printf("Yes\n"): printf("No\n"); 
isPowerOfTwo(64)? printf("Yes\n"): printf("No\n"); 
return 0; 
} 
Logic 1: to check number is even or odd
Logic 1: to check number is even or odd
Logic 1: to check number is even or odd
Logic 1: to check number is even or odd
Logic 1: to check number is even or odd


logic 1: explanation:

    01100010
&   00000001
    --------
    00000000
 
logic 2 : exp
 
1         00000001    (same as 1<<0)
1<<1      00000010
1<<2      00000100
1<<3      00001000
1<<4      00010000
1<<5      00100000
1<<6      01000000
1<<7      10000000 


logic 3 : exp
 
    01111000    (120 in binary)
|   00000100    (1<<2)
    --------
    01111100 


Reference:

https://www.quora.com/How-do-you-set-clear-and-toggle-a-single-bit-in-C

https://www.hackerearth.com/practice/notes/bit-manipulation/

http://see-programming.blogspot.in/2013/07/c-program-to-set-reset-check-clear-and.html





logic 7: size of int and int long

[tselva@xxx]$ cat size_int_long.c
#include <inttypes.h>
#include <stdio.h>
int main() {
  printf( "    short int: %zd\n" , sizeof(short int) ) ;
  printf( "          int: %zd\n" , sizeof(int) ) ;
  printf( "     long int: %zd\n", sizeof(long int) ) ;
  printf( "long long int: %zd\n", sizeof(long long int) ) ;
  printf( "       size_t: %zd\n", sizeof(size_t) ) ;
  printf( "        void*: %zd\n\n", sizeof(void *) ) ;
  printf( "PRIu32 usage (see source): %"PRIu32"\n" , (uint32_t) 42 ) ;
  return 0;
}
[tselva@xxxx]$ ./a.out
    short int: 2
          int: 4
     long int: 4
long long int: 8
       size_t: 4
        void*: 4
PRIu32 usage (see source): 42
logic 9: why do we need L,UL representaion

what is meant by UL represenation?
var |= (1UL << 5); // note the brackets to force shift before ORing
1UL - UL represents unsigned long i.e. 32 bit representation of 1
point 1:
A decimal number like -1,1,2,12345678, etc. without any suffix will get the smallest type it will fit, starting with intlonglong long.
An octal or hex number like 0, 0123, 0x123, 0X123 without any suffix will get the smallest type it will fit, starting with intunsignedlongunsigned longlong longunsigned long long.
Point 2:
Because numerical literals are of typicaly of type int. The UL/L tells the compiler that they are not of type int, e.g. assuming 32bit int and 64bit long
long i = 0xffff;
long j = 0xffffUL;
Here the values on the right must be converted to signed longs (32bit -> 64bit)
  1. The "0xffff", an int, would converted to a long using sign extension, resulting in a negative value (0xffffffff)
  2. The "0xffffUL", an unsigned long, would be converted to a long, resulting in a positive value (0x0000ffff)
Ref: https://stackoverflow.com/questions/25605777/c-literal-suffix-u-ul-problems
https://stackoverflow.com/questions/13134956/what-is-the-reason-for-explicitly-declaring-l-or-ul-for-long-values









Sunday, July 27, 2014

bit list / bitmap / bitvector

simple bit list implementation

source: http://easwer.wordpress.com/2010/11/09/bit-vectors-in-c/


#include<stdio.h>
#include<stdlib.h>
char *create_set(int n)
{
	return calloc(n,sizeof(char));

}
addto_set(char *address,int value)
{
	address[value/8] = address[value/8] | ( 1 << (value%8));
}
deletefrom_set(char *address,int value)
{	
	address[value/8] = address[value/8] & ~(1 << (value%8));
}
int ismember(char *address,int value)
{	
	return ( address[value/8] & ( 1 << (value%8) ) );	
}	
main()
{
	char *s;
	s = create_set(10);
	addto_set(s,10);
	addto_set(s,11);
	addto_set(s,12);
	addto_set(s,13);
	addto_set(s,18);
	addto_set(s,19);
	addto_set(s,21);
	addto_set(s,22);
	addto_set(s,2);
	addto_set(s,24);
	addto_set(s,25);
	addto_set(s,26);
	addto_set(s,27);
	addto_set(s,28);
	deletefrom_set(s,10);
	if (ismember(s,5) ) printf("element present \n");
	else printf("not present \n");
}

	
What is bit list:
* Please refer wikipedia
   http://en.wikipedia.org/wiki/Bit_array

http://alg-code.blogspot.in/2011/02/bit-arrays-and-bit-vectors.html



Application code:

* http://www.careercup.com/question?id=14952124


Etc:

* https://github.com/noporpoise/BitArray


recursion

General rule of recursion

1. instead of loop statement iteration, we manually do iteration by 

   calling the function again and again.

2. the purpose(ex. strcpy or strcmp done only one time in the base case)

3. have to carefully choose the else condition. otherwise that statement will be

executed in the all cases.

4. have to carefully put the return statment otherwise intended program will

return false vales.  

5. in recursion terminating statement can be in if case( that is return case)

   and calling the function itself can be in else case(which make loop) or vice versa depending on the requirement.

 


string length using iterative and recursion:


a1. strlen (without array length variable)
int strlen_r(char *s)
{
 if (*s=='\0') return 0;
 else return(1 + strlen_r(s+1));
} 
source: http://www.sparknotes.com/cs/recursion/examples/section1.rhtml

a2. strlen
int strlen(char *str,int len)
{
 if(str[len]=='\0')
return len;
else
 return strlen(str,++len);
* a2 using indexing operation and a1 is not using indexing operator
but have to check for integers called with this.



string comparison using ecursion:

a1. 

int strcmp_r(char *s, char *t)
{
 if (*s == '\0' || *s != *t) return *s - *t;
 else return(strcmp_r(s+1, t+1));
}
 
* very best and effective solution. superb above code!!! 
source: http://www.sparknotes.com/cs/recursion/examples/section1.rhtml 
 
a2. 
 

string copy using ecursion:

a1. recursive optimized approach:

char *strcpy_r(char *s, char *t)
{
 if ((*s = *t) != '\0') strcpy_r(s+1, t+1);
 return s;
}

* here reason for not giving the s in the else statement is, every time s will be returned.
  So in the first call of this function orignal 0th location memory of destination will be
  returned
 * and s++ is avoided and s + 1 given due.to not increment the original pointer
 
for more info refer the sourcee
source: http://www.sparknotes.com/cs/recursion/examples/section1.rhtml 

Technique on programming

Technique 1 :
Length of the string without loop and without recursion (only using printf and gets)

#include <stdio.h>
int main()
{
     char str[100];
     printf("Enter a string: ");
     printf( "\rLength is: %d",
              printf("Entered string is: %s\n", gets(str)) - 20
           );
     return 0;
}
Output:
Enter a string: GeeksforGeeks
Entered string is: GeeksforGeeks
Length is: 13
The idea is to use return values of printf() and gets().
gets() returns the entered string length.
printf() returns the number of characters successfully written on output.

Source:  http://www.geeksforgeeks.org/find-length-string-without-strlen-loop/


technique 2:

  1. to get the long line with spcae, you can only use gets(string name). scanf will not help
  2. to compare the space of the string you can use if(str[index] == 32). since the 32 is the ASCII value for the 32. refer ASCII table at http://www.asciitable.com/

Example:

SELVATHA-M-V0HE:test selvatha$ more scan.c 
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
        char name1[100]={0};
        char name2[100]={0};
        printf("\n================================ \n");
        printf("\n Scanning using scanf without space");
        printf("\n================================ \n");
        printf("\n enter the name1\t:");
        scanf("%s",name1);
        printf("\n string is \t:%s\n",name1);
        printf("\n================================ \n");
        printf("\n Scanning using gets with space");
        printf("\n================================ \n");
        printf("\n enter the name2\t:");
        gets(name2);
        printf("\n string is \t:%s\n",name2);
        return 0;
}
SELVATHA-M-V0HE:test selvatha$ ./a.out 

================================ 

 Scanning using scanf without space
================================ 

 enter the name1	:selva kumar hi 

 string is 	:selva

================================ 

 Scanning using gets with space
================================ 

warning: this program uses gets(), which is unsafe.  ---> 
---> program terminated as it wont allow us to use the gets which create a buffer
overflow. this output is waste. 
 enter the name2	:
 string is 	: kumar hi

Awareness:

A1. strcpy will do null termination :-)
       but strncpy will not do null termination :-(


stcpy:

The strcpy() function copies the string pointed to by src, including
       the terminating null byte ('\0'), to the buffer pointed to by dest
 
stncpy:
       The strncpy() function is similar, except that at most n bytes of src
       are copied.  Warning: If there is no null byte among the first n
       bytes of src, the string placed in dest will not be null-terminated.


A simple implementation of strncpy() might be:

           char *
           strncpy(char *dest, const char *src, size_t n)
           {
               size_t i;

               for (i = 0; i < n && src[i] != '\0'; i++)
                   dest[i] = src[i];
               for ( ; i < n; i++)
                   dest[i] = '\0';

               return dest;
           }

source: http://man7.org/linux/man-pages/man3/strncpy.3.html

But what strcpy will do if the source string dont have a room for the null termination:

 selvatha$ more test.c

#include<stdio.h>
#include<string.h>
int main() {
        char name[7];
        strcpy(name,"1234567");
        printf("\n %s \n",name);
        return 0;
}

SELVATHA-M-V0HE:Unused Desktop selvatha$ gcc test.c
SELVATHA-M-V0HE:Unused Desktop selvatha$ ./a.out
Abort trap: 6

After giving the space for NULL termination:



#include<stdio.h>
#include<string.h>
int main() {
        char name[7];
        strcpy(name,"1234567");
        printf("\n %s \n",name);
        return 0;
}

SELVATHA-M-V0HE:Unused Desktop selvatha$ gcc test.c
SELVATHA-M-V0HE:Unused Desktop selvatha$ ./a.out

 123456

strchr:


This returns a pointer to the first occurrence of the character c in the string str, or NULL if the character is not found.

Example:

The following example shows the usage of strchr() function.
#include <stdio.h>
#include <string.h>

int main ()
{
   const char str[] = "http://www.tutorialspoint.com";
   const char ch = '.';
   char *ret;

   ret = strchr(str, ch);

   printf("String after |%c| is - |%s|\n", ch, ret);
   
   return(0);
}
Let us compile and run the above program, this will produce the following result:
String after |.| is - |.tutorialspoint.com|


source: www.tutorialspoint.com/c_standard_library/c_function_strchr.htm

sprintf

char *itoa(int n)
 {
 char *retbuf = malloc(25);
 if(retbuf == NULL)
  return NULL;
 sprintf(retbuf, "%d", n);
 return retbuf;
 }
source: http://www.eskimo.com/~scs/cclass/int/sx5.html 

tech2:

%u used for printing the &var
%d itself used for sizeof() operator

tech3:
expr1 << expr2 == expr1 *  2expr2
10 * 32       ==  10 << 5 (becuase 32 = 25)
expr1 >> expr2 == expr1 /  2expr2 

40 / 4                     == 40 >> 2      (becuase 4 = 22)

tech 3:

pointer array to store the character data array


  • char name[max][size]  == char *ptr[ ]  (so char *ptr[ ] can be used to rx datat array in the funcion)
  •  char *ptr[] == char **ptr (so char **ptr can be used to rx char *ptr[ ]in the funcion)
  • so i guess char name[max][size] also can be received via char ** in the function call


example:
http://www.netospgm.blogspot.in/2014/08/pointer-array-and-its-advantage.html
http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=%2Fcom.ibm.vacpp6m.doc%2Flanguage%2Fref%2Fclrc03example_prog_pointers.htm


tech 4:


  • to print the address use %x or %p 

example:


#include <stdio.h>

int main ()
{
   int  var = 20;   /* actual variable declaration */
   int  *ip;        /* pointer variable declaration */

   ip = &var;  /* store address of var in pointer variable*/

   printf("Address of var variable: %x\n", &var  );

   /* address stored in pointer variable */
   printf("Address stored in ip variable: %x\n", ip );

   /* access the value using the pointer */
   printf("Value of *ip variable: %d\n", *ip );

   return 0;
}

tech 5:



   
b & 0xff gets the last byte of b


root@selvakumar-Lenovo-B460e:/C_pgms/memory# cat last_byte.c #include<stdio.h> /* program to mask last one byte of the given number*/ int main() { short a=0x0101; // two byte integer in hex format short b; printf("\n%d\n",a); b = a & 0xff; // this mask last 1 byte printf("\n%d\n",b); return 0; } root@selvakumar-Lenovo-B460e:/C_pgms/memory# gcc last_byte.c root@selvakumar-Lenovo-B460e:/C_pgms/memory# ./a.out 257 1 root@selvakumar-Lenovo-B460e:/C_pgms/memory#






tech 6;

size of void * and char * is 4

http://www.netospgm.blogspot.in/2014/08/sizeof-void-char.html

tech 7: how do memset on string array:

void *memset(void *str, int c, size_t n)

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

int main ()
{
   char str[50];

   strcpy(str,"This is string.h library function");
   puts(str);

   memset(str,'$',7);
   puts(str);
   
   return(0);
}
This is string.h library function
$$$$$$$ string.h library function
Refer:https://www.tutorialspoint.com/c_standard_library/c_function_memset.htm



Techniqure 8:

To define a function as static, the static keyword has to be included in the signature of the function. It does not matter in which position the keyword is mentioned, it can be inserted before or after the return type and other optional keywords, but must be inserted before the function name


so "static void test()" 
or "void static test()".
 both are same. but static keyword should be before function name

Reference: https://wr.informatik.uni-hamburg.de/_media/teaching/wintersemester_2013_2014/epc-1314-fasselt-c-keywords-report.pdf

Technique 9:

- int a[10] we can assingn to int *p as p=a . as like normal single interger variable
- we can access the arrary variable using pointer with index operator as p[i]. see second example. so in the function we can receive the array using pointer variable and access that poiter inside function using index operator.
- or we can access the array using pointer as *(p+i)

#include <stdio.h>
int main ()  
{    int i;   
        int AR [] = { 10, 20, 30, 40, 50 };
        int *pAR = AR;    
        clrscr();
        printf("\nAR = %p\t &AR[0] = %p\t pAR = %p\n",AR,&AR[0],pAR);
        for (i=0;i<5;i++)      
                printf("*pAR = %d\t AR[%d] = %d\n",*pAR++, i, AR[i]);
        return 0;
}


int *pAR &AR[0];
The values of elements of the array AR [4] may be obtained from its pointer pAR in the following manner:
* pAR = 10
*(pAR+l)= 20
*(pAR+2)= 30
*(pAR+3)= 40

[tselva@bng-junos-d037 /b/tselva/bcopy/bk_copy_needed/copy-needed/work_tips_dir/sample_c_program]$ cat array_pointer.c
#include <stdio.h>
int main ()
{
  int i;
  int AR [] = { 10, 20, 30, 40, 50 };
  int *pAR = AR;
  printf("\nAR = %p\t &AR[0] = %p\t pAR = %p\n",AR,&AR[0],pAR);

  for (i=0;i<5;i++)
    printf("pAR[%d]=%d\n",i,pAR[i]);
  for (i=0;i<5;i++)
    printf("*pAR = %d\t AR[%d] = %d \n",*pAR++, i, AR[i]);
    return 0;
}
[tselva@bng-junos-d037 /b/tselva/bcopy/bk_copy_needed/copy-needed/work_tips_dir/sample_c_program]$ ./a.out

AR = 0xffffc838 &AR[0] = 0xffffc838 pAR = 0xffffc838
pAR[0]=10
pAR[1]=20
pAR[2]=30
pAR[3]=40
pAR[4]=50
*pAR = 10 AR[0] = 10
*pAR = 20 AR[1] = 20
*pAR = 30 AR[2] = 30
*pAR = 40 AR[3] = 40
*pAR = 50 AR[4] = 50

Ref: http://ecomputernotes.com/what-is-c/function-a-pointer/one-dimensional-array-with-pointer

Technique 10: character array

http://control.ucsd.edu/mauricio/courses/mae9/lectures/lecture5.pdf

Technique 11: sizeof vs strlen:


/* 
 * sizeof_vs_strlen.c -- program shows difference between using sizeof and
 * strlen with array and string
 */
#include <stdio.h>
#include <string.h>
 
int main(void)
{
    char msg[] = {'c','h','r','i','s','t','o','p','h','e','r'};
                                 /* Character array */ 
    char name1[] = "christopher";       /* character array */
    char *name2 = "christopher";        /* string literal */
 
    printf("sizeof: size of char array msg[] \"%s\" is %d bytes!\n",
           msg, sizeof(msg));
    printf("strlen: size of char array msg[] \"%s\" is %d bytes!\n",
           msg, strlen(msg)); 
 
    printf("sizeof: size of char array name1[] \"%s\" is %d bytes!\n",
           name1, sizeof(name1));
    printf("strlen: size of char array name1[] \"%s\" is %d bytes!\n",
           name1, strlen(name1));
 
    printf("sizeof: size of string \"%s\" is %d bytes!\n",
           name2, sizeof(name2));
    printf("strlen: size of string \"%s\" is %d bytes!\n",
           name2, strlen(name2));
 
    return 0;
}
Output follows:
sizeof: size of char array msg[] "christopher" is 11 bytes!
strlen: size of char array msg[] "christopher" is 11 bytes!
sizeof: size of char array name1[] "christopher" is 12 bytes! 
strlen: size of char array name1[] "christopher" is 11 bytes!
sizeof: size of string "christopher" is 8 bytes!
strlen: size of string "christopher" is 11 bytes!
Ref: http://www.sanfoundry.com/c-tutorials-size-array-using-sizeof-operator-strlen-function/

Technique 12:
This will not work:
char *myfunc1()
{
char temp[] = "string";
return temp;
}


char *myfunc2()
{
char temp[] = {'s', 't', 'r', 'i', 'n', 'g', '\0'};
return temp;
}


int main()
{
puts(myfunc1());
puts(myfunc2());
}




The returned pointer should be to a static buffer (like static char buffer[20];), or to a buffer passed in by the caller function, or to memory obtained using malloc(), but not to a local array. 

This will work:
char *myfunc()
{
char *temp = "string";
return temp;
}

int main()
{
puts(someFun());
}

Ref: http://vijayinterviewquestions.blogspot.in/search?q=strcpy


Tehcnique 13:
A to Z ascii value = 65 to 90

a to z ascii value = 97 to 122




int
strcmp(const char *str1, const char *str2)

Output:
  • if Return value < 0 then it indicates str1 is less than str2.
  • if Return value > 0 then it indicates str2 is less than str1.
  • if Return value = 0 then it indicates str1 is equal to str2.

Technique 14:
* INADDR_ANY is used when you don't need to bind a socket to a specific IP. When you use this value as the address when calling bind(), the socket accepts connections to all the IPs of the machine.
 This allowed your program to work without knowing the IP address of the machine it was running on, or, in the case of a machine with multiple network interfaces, it allowed your server to receive packets destined to any of the interfaces.
If you wish to bind your socket to localhost only, the syntax would be my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1");, then call bind(my_socket, (SOCKADDR *) &my_sockaddr, ...)
* Example: . For example, suppose that a host has interfaces 0, 1 and 2. If a UDP socket on this host is bound using INADDR_ANY and udp port 8000, then the socket will receive all packets for port 8000 that arrive on interfaces 0, 1, or 2. If a second socket attempts to Bind to port 8000 on interface 1, the Bind will fail since the first socket already ``owns'' that port/interface.



Ref:
https://www.cs.cmu.edu/~srini/15-441/F01.full/www/assignments/P2/htmlsim_split/node18.html

https://stackoverflow.com/questions/16508685/understanding-inaddr-any-for-socket-programming-c


Technique 15:
sprintf vs snprintf

Both will give the result you want, but snprintf is more generic, and will protect your string from overruns no matter the format string given. In addition, because snprintf(or sprintf for that matter) adds a final \0 , you should make the string buffer one byte bigger, char buff[MAXLEN + 1] 
snprintf ... Writes the results to a character string buffer. (...) will be terminated with a null character, unless buf_size is zero.

Technique 16:
In short: memset require more assembly operations then bzero . You probably shouldn't use bzero , it's not actually standard C, it was a POSIX thing. And note that word "was" - it was deprecated in POSIX.1-2001 and removed in POSIX.1-2008 in deference to memset so you're better off using the standard C 

Ref: https://stackoverflow.com/questions/17096990/why-use-bzero-over-memset

Ref: 
https://stackoverflow.com/questions/7706936/is-snprintf-always-null-terminating

All in all URL (networks,kernel,system,c)
http://blmrgnn.blogspot.in/2014/06/memory-layout-of-c-program-code-data.html

Techniqure 17:
enum starts with 0 if we dont specify any default value



Technique 18:

Returning the pointer from the function:

https://www.geeksforgeeks.org/return-local-array-c-function/

Ref: https://www.tutorialspoint.com/cprogramming/c_return_pointer_from_functions.htm

Technique 19: deep copy and shallow copy in the C

A shallow copy in this particular context means that you copy "references" (pointers, whatever) to objects, and the backing store of these references or pointers is identical, it's the very same object at the same memory location.
A deep copy, in contrast, means that you copy an entire object (struct). If it has members that can be copied shallow or deep, you also make a deep copy of them. Consider the following example:



typedef struct {
    char *name;
    int value;
} Node;

Node n1, n2, n3;

char name[] = "This is the name";

n1 = (Node){ name, 1337 };
n2 = n1; // Shallow copy, n2.name points to the same string as n1.name

n3.value = n1.value;
n3.name = strdup(n1.name); // Deep copy - n3.name is identical to n1.name 
                           // regarding
                           // its *contents* only, but it's not anymore the 
                           // same pointer


And  Using struct:

We can wrap array in a structure/class and return an 
instance of the struct/class. The reason for this 
work is, array members of structures are deeply 
copied. In below program deep copy happens when 
we returned instance is copied in main.
#include <stdio.h>
  
struct arrWrap {
    int arr[100];
};
  
struct arrWrap fun()
{
    struct arrWrap x;
  
    x.arr[0] = 10;
    x.arr[1] = 20;
  
    return x;
}
  
int main()
{
    struct arrWrap x = fun();
    printf("%d %d", x.arr[0], x.arr[1]);
    return 0;
}



Ref:  

 

Technique 20:

How to pass an entire array to a function as an argument?

In the above example, we have passed the address of each array element one by one using a for loop in C. However you can also pass an entire array to a function like this:

Note: The array name itself is the address of first element of that array. For example if array name is arr then you can say that arr is equivalent to the &arr[0].

#include <stdio.h>
void myfuncn( int *var1, int var2)
{
	/* The pointer var1 is pointing to the first element of
	 * the array and the var2 is the size of the array. In the
	 * loop we are incrementing pointer so that it points to
	 * the next element of the array on each increment.
	 *
	 */
    for(int x=0; x<var2; x++)
    {
        printf("Value of var_arr[%d] is: %d \n", x, *var1);
        /*increment pointer for next element fetch*/
        var1++;
    }
}

int main()
{
     int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
     myfuncn(var_arr, 7);
     return 0;
}

Ref: https://beginnersbook.com/2014/01/c-passing-array-to-function-example/


Technique 21: convert the string to upper case:

A = 65
a = 97
A-a= 32

Example:

#include <stdio.h>
#include <string.h>
int main() {
   char s[100];
   int i;
   printf("\nEnter a string : ");
   gets(s);
   for (i = 0; s[i]!='\0'; i++) {
      if(s[i] >= 'a' && s[i] <= 'z') {
         s[i] = s[i] -32;  // s[i] = s[i]+32 to conver into lower case
      }
   }
   printf("\nString in Upper Case = %s", s);
   return 0;
}