Sunday, November 25, 2012

C puzzles

1. What is the output of following C program ?

int main()
{
func(5);
return 0;
}
func(int a)
{
int a;
a=10;
printf("%d",a);
}


=> This will end up in error.


error: 'a' redeclared as different kind of symbol
 
Reason: As int a is a local variable it will be stored in stack, when once 
again a is re-declared it will thrown an error.
 
2.What is the output of following C program ?
 
int a=5;
int main()
{
func(5);
return 0;
}
func(int a)
{
a=10;
printf("%d",a);
}
 
Output => 10
 
Reason: In statement int a =5; a will be stored in data segment of memory, 
where as int a in func(int a) will be stored in stack. So no redeclaration 
scenario like earlier case.
 
3. In the below program 'a' is a global variable. So it can be accessed by 
all functions.Is there any way to restrict the access of variable 'a' from 
func3() ?

int a;
int main()
{
func1();
func2();
func3();
return 0;
}
func1()
{

}
func2()
{

}
func3()
{

}

Answer => Yes. Look into the previous example. By declaring 'a' inside func3() 
we can restrict access to global variable 'a'

int a;
int main()
{
func1();func2();func3();
return 0;
}
func1()
{

}
func2()
{

}
func3()
{
int a;
}
 
4. What is the output of the following two programs?
 
int main()
{
char *p = NULL;
printf("%d %d",p,p++);
return 0;
}
 
Output => 0 1
Reason: NULL is always stored in the zeroth location. Increment pointer of char type
will shift to position 1 as char takes 1 byte.
  
int main()
{ 
int *p = NULL;
printf("%d %d",p,p++);
return 0;
}
 
Output => 0 4
Reason: NULL is always stored in the zeroth location. Increment pointer of int type
will shift to position 4 as int takes 4 byte. 
 
5. What is the prototype of malloc and free ?
 
Answer =>
 
void *malloc(size_t size); 
void free(void *ptr);  

size_t is of unsigned type.

 
  

Friday, November 9, 2012

How to compile only the last modified C file in the directory using Makefile?

Assume work is the current directory. Assume there are p1.c, p2.c, p3.c files are there. Each .c file has main function. I want to compile only the last modified file using Makefile. Is it possible ?

Yes.

Write a Makefile[ vim Makefile in linux terminal] and type below commands.


SRC=$(shell ls -rt | tail -1)
test: $(SRC)
        gcc -o test $(shell ls -rt | tail -1)

Save the Makefile using [escape :wq!]

Execute using make command.
./test will give the output of last modified file. If I have modified p2.c it will show output of p2.c.

chmod - change mode


Exectute below commands

ls –l filename

Now observe the result

chmod 644 filename

ls –l filename

Now observe the result after doing chmod. When you observe you will find out the file access permissions would have changed.

user | group | others
6          4          4
- rw -    r - -      r - -


rwx    Mode
111       7
110       6
101       5
100       4
011       3
010       2
001       1
000       0

r = read only
w = write only
x = execute only

To tar and untar folder


Assume "work" is the directory you want to tar. [ Tar is nothing but compressing the file to zip folder]
Execute the below command to tar folder
tar –czf work.tar.gz work
To untar the tar folder. [ Untar is extracting the files]
Execute below command to untar folder.
tar –xzvf work

Linux compiler version: How to find Linux compiler version ?

Execute "gcc -v" in Linux terminal

Wednesday, November 7, 2012

Enum Enumerations

#include<stdio.h>
enum day
{
sun,
mon,
tue,
wed,
thur,
fri,
sat
}which_day;
 
int main()
{
which_day = mon;
 
switch(which_day)
{
case sun: printf("Today is sunday");
          break;
 
case mon: printf("Today is monday");
          break;
 
case tue: printf("Today is tuesday");
          break;
 
case wed: printf("Today is wednesday");
          break;
 
case thur: printf("Today is thursday");
          break;
 
case fri: printf("Today is friday");
          break;
 
case sat: printf("Today is saturday");
          break;
 
}
return 0;
}
 
Output: Today is monday

Monday, October 29, 2012

Memmove implementation in C



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

int main()
{
char data1[] = "0123456789";
char data2[] = "0123456789";
char data3[] = "0123456789";
char data4[] = "0123456789";

memcopy(&data1[5],&data1[3],5);
memcopy(&data2[3],&data2[5],5);

memove(&data3[5],&data3[3],5);
memove(&data4[3],&data4[5],5);

printf("MemCopy=%s\nMemCopy=%s\nMemMove=%s\nMemMove=%s\n", data1,data2, data3, data4);
return 0;
}


//Memmove implementation in C


  void memove(void* destination,void* source,unsigned int amount)
{
char *dest = (char *)destination; // Converting void pointer into char pointer
char *src = (char *)source;

int loop_count=0; //for loop count
int count=0;
int flag = 0; // To check for overlapping address

//Loop to determine overlapping address
for(loop_count=0;loop_count<amount;loop_count++)
{
if((src+loop_count) == dest) // For destination first byte within source range
{
count = amount;
while(amount--)
{
*(dest+amount) = *(src+amount);
}
amount = count;
flag = 1;
}
else if((dest+loop_count) == src) // For destination last byte within source range
{
memcopy(dest,src,amount);
flag =1;
}
}
if(flag == 0) // No overlapping of addresses
memcopy(dest,src,amount);
}


//Memcpy implementation in C


  void memcopy(void* destination,void* source,int amount)
{
char *dest = (char *)destination;
char *src = (char *)source;

while(amount--) // Copying from starting
{
*dest++=*src++;
}
}





Friday, October 26, 2012

C program to find difference between two times.

#include <sys/time.h>
#include<stdio.h>

int main()
{
struct timeval current_time;
struct timeval past_time;

gettimeofday(&current_time,NULL); // This function will update structure timeval  with current time stamp.

past_time.tv_sec = 1351257149; //.tv_sec holds time value in seconds. I have hard coded a value for it directly.

printf("The difference between past and present time = %ld",current_time.tv_sec-past_time.tv_sec );

return 0;
}

ICMP - Internet control message protocol



ICMP basically provides a way to report the error messages which are encountered in network to the original source.

Do you know the protocol used in ping?

Well, the answer is ICMP. It is implemented using ICMP echo request and ICMP echo response. If a system receives an ICMP echo request, it will generate an ICMP echo response and sends it to the original source.

ICMP echo request is nothing but PING.

ICMP echo request packet


0                                                      7 8                                                      15  16                                                  31
                       TYPE
CODE
                 CHECKSUM

                       IDENTIFIER
SEQUENCE NUMBER

                                                                             OPTIONAL DATA

ICMP echo reply packet


0                                                      7 8                                                      15  16                                                  31
                       TYPE
                       CODE
                 CHECKSUM

This is not used( So we can make bits set to zero)

                                                                             OPTIONAL DATA

TYPE Field                                          ICMP Message Type
0                                                             Echo Reply
8                                                             Echo Response
CODE Value                                        Meaning
0                                                              Network Unreachable

CHECKSUM

 ICMP message header checksum (additive algorithm is used to calculate checksum) 

IDENTIFIER and SEQUENCE NUMBER

These fields are used to match echo requests to corresponding echo replies. 

DATA

 It is variable length; the data which is to be returned to sender will be present here.

ARP - Address resolution protocol


On the same physical network, a host can find out the physical address of another host given only the target host’s IP address.

How ARP works?

Consider Host A want to send data to Host B.

Host A broadcasts a packet asking host with IP address IPB to respond with itsphysical address. When host B receives the packet, it will respond to Host A with its physical address. Later Host A uses Host B’s physical address to send data directly.

Systems that use ARP will maintain a cache where it will store all IP address and corresponding physical address when it receives ARP replies.Cache is a component that stores data so that future requests for that data can be served faster.

ARP PACKET

0               7  815  16                 23  24                                            31
HARDWARE TYPE
PROTOCOL TYPE
Hardware address Length
Protocol address Length
Operation Code
Sender Hardware Address (0-3 Octets)
Sender Hardware Address(4-5Octets)
Sender IP Address(0-1Octets)
Sender IP Address(2-3Octets)
Target Hardware address(0-1Octets)
Target Hardware address(2-5Octets)
Target IP address(0-3Octets)




HARDWARE TYPE                        HARDWARE Interface type
0                                                           Ethernet

PROTOCOL TYPE                         Networklevel protocol address
      0x0800                                                 IpV4

Operation Code                               Request-Response
     1                                                           ARP request
     2                                                           ARP response

When ARP request is made by Host A, the Target Hardware address fields will be empty. The missing fields will be filled by Host B and it sends ARP reply.

Thursday, October 25, 2012

C puzzles

#include "stdio.h"
Can we include stdio.h in double quotes instead of angle brackets?

Answer: Yes

If the filename is enclosed within angle brackets, the file is searched in the path where compiler includes standard header files. If the filename is enclosed within double quotes, we are telling the compiler that search for this header file in current source directory too.

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

#include<stdio.h>
int main()
{
char *p=NULL;
int *a =NULL;
p++;
a++;
printf("%u %u",p,a);
return 0;
}
Output: 1 4

The Address of Null pointer is 0. So the increment will end up in 1 for char pointer as char takes 1 byte and 4 for int pointer as int takes 4 bytes.



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

#include<stdio.h>
int main()
{
char *p="abcd";
p[2]='C';
printf("%s",p);
return 0;
}
Output: Segmentation fault

“abcd” will be stored in read only section of memory, so we cannot change the value.



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

#include<stdio.h>
#include<string.h>
int main()
{
char *str;
str=(char *)malloc(sizeof(char)*100);
strcpy(str,"abcd");
printf("%s",str);
str[2]='C';
printf(" %s",str);
return 0;
}
Output: abcd abCd

We have allocated memory to "abcd". So we can modify it.



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

int main()
{
char a='a';
char *p;
printf("%d",sizeof(p));
return 0;
}
Output: 4

Pointer always stores address of a variable. Address is an integer value. Hence it takes 4 bytes.



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

int main()
{
int a=1;
printf("%d %d %d %d %d %d",++a,a++,++a,a,a++,++a);
return 0;
}
Output: 6 4 4 3 2 2

Processing happens from right to left. Start from right and increment variable ‘a’.



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

int main()
{
int a=1;
int b=0;
int c=0;
c=a++ + a++;
b=a++ + ++a;
printf("%d %d %d\n",c,b,a);
printf("%d %d %d %d %d %d\n",a++,a++,a++,a++,a++,a++);
printf("%d %d %d %d %d %d",++a,a++,++a,a,a++,++a);
return 0;
}
Output: 2 8 5
10 9 8 7 6 5
16 14 14 13 12 12



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

#include<stdio.h>
int main()
{
char *p="abc";
*p++;

printf("%s",p);
return 0;
}
Output: bc

Pointer will be pointing to abc’s first address which is the address of a. When pointer is incremented, it will be pointing to ‘b’. So when we print it will show string from ‘b’ that is “bc”.



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

#include<stdio.h>
int main()
{
char *p="abc";
char a;
a=*++p;

printf("%c %s",a,p);
return 0;
}
Output: b bc



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

#include<stdio.h>
int main()
{
char *p="abcdefgh";

printf("%d %d %d %c %c",p,p++,++p,*p++,*++p);
return 0;
}
 Output: 134513788  134513787  134513787  b b



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

#include<stdio.h>
int main()
{
char *p="abc";
*p++;

printf("%s",p);
p--;
printf(" %s",p);
return 0;
}
Output: bc abc



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

int main()
{
char a='a';
char *p;
p=&a;
printf("%u %u",p,&a);
p++;
printf(" %u %u",p,&a);
return 0;
}
Output: 3220097815 3220097815 3220097816 3220097815



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

Write a C program to call by itself 5 times (recursively) without using any global variables.

#include<stdio.h>
int call();
int main()
{
call();
return 0;
}

int call()
{
static int count = 0;
count++;
if(count == 6)
{
        exit(0);
}
else
{
        printf("count = %d\n",count);
        call();
}
}

Using static variable to retain value between various function calls.



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

Why is volatile keyword used?
Answer: To tell compiler not to optimize the code.
Example:
static int noChange = 0;

void vol()
{
while (noChange!= 5)
{
                Printf(“hi”);
         }
}

Compiler will think noChange cannot become 5 and replace noChange!= 5 with true value.

static int noChange = 0;

void vol()
{
while (1)
{
                Printf(“hi”);
         }
}
So to avoid this type of optimization we make static int noChange as static volatile int noChange.



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

Can static variables be declared outside the main function?
Answer: Yes.
Variables declared as static outside any function definitions are visible throughout that file.



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

Can we use extern to a static variable?
Answer: No.
The purpose of static variable is to make that a variable private to the source file where it is declared.



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

How do you avoid structure padding?
Answer: You can do it using pragma



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

What is the difference between scope and lifetime of a variable?
Scope: It is the place where you can access the variable.
Lifetime: Time for which the variable will be alive.
Example
Void Abc();
int main()
{
Abc();
return 0;
}
void Abc()
{
                int count = 0;
                printf(“%d”,count);
}

Let us take count variable
Scope of count variable: You can access count variable only inside abc() function. So scope is local to function block.
Lifetime of count variable: From the beginning of function abc() till end of function abc() we can use variable count. So lifetime becomes “till control remain within the block”.



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

What is the difference between function definition and declaration?

Consider below example
Void Abc();
int main()
{
Abc();
return 0;
}
void Abc()
{
                int count = 0;
                printf(“%d”,count);
}
Function definition: Where the logic for the function is written.
void Abc()
{
                int count = 0;
                printf(“%d”,count);
}

Function declaration: It is like a signature to let compiler know that there is a function with name Abc();
Void Abc();

Function call: Calling the function to execute the function definition
Abc();